javascript - ES6 模块如何在 Node/Express 路由应用程序中与 app.get 一起使用?
问题描述
我决定在 NodeJS/Express 项目中使用新的 ES6 导出而不是使用模块导出。我正在阅读 MDN 文档,它说 export 的使用方式如下:
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);
推荐阅读
- node.js - 如何获取我的机器人可以看到的所有用户?
- python - Python 中 asyncio 的默认并发级别是多少?
- unity3d - Unity 中用于旋转的圆形滑块
- c++ - 将奇数大小的 int 枚举放入非常小的结构中?
- django - python 无法打开文件'manage.py' - “heroku run python manage.py migrate 命令输入”
- javascript - 使用 Datatables 列可见性和 stateSave 时如何保留或调用外部复选框状态
- python - 通过省略循环和强制转换来优化 numpy 最小二乘
- python - 如何检查字段是否在 pymongo 的特定文档中?
- angular - Socket.io 未在客户端接收消息
- c - gcc 会优化一个常量变量的开关吗