我决定在NodeJS / Express项目中使用新的ES6导出,而不是使用模块导出。我正在阅读MDN文档,它说导出的用法如下:
export function draw(ctx, length, x, y, color) {
ctx.fillStyle = color;
ctx.fillRect(x, y, length, length);
在这里,我试图在此app.get
函数中以相同的方式使用它,但是我的编辑器抛出语法错误。我应该使用其他格式吗?-本质上来说,我试图将路由容器分成单独的文件进行组织-然后最后将它们导入回到我的主要app.js文件中,以便使用express进行路由声明。
export app.post('/exampleroute', async (req, res) => {
...
});
// Error: Declaration or Statement expected.
您必须导出一个值(默认值或命名变量)。
的返回值app.post()
没有用。
要么导出函数:
export const myRouteHandler = async (req, res) => {
...
};
接着:
import { myRouteHandler } from "./myModule";
app.post('/exampleroute', myRouteHandler)
或者,导出路由器:
import express from 'express';
export const router = express.Router();
router.post('/exampleroute', async (req, res) => {
...
});
然后导入并使用该代码:
import { router } from "./myModule";
app.use("/", router);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句