【发布时间】:2023-01-10 13:20:54
【问题描述】:
当我尝试启动我的 Node/Express 应用程序时出现以下错误。该问题似乎是由使用 module.exports 从同一文件导出多个函数引起的。也就是说,应用程序启动正常,路由中间件仅在我导出单个函数时才工作。
Error: Route.get() requires a callback function but got a [object Object]
这是路线
router.get('/check', MW.isAuth, function (req, res) { // including MW.otherMiddleware here causes error
res.send({ messsage: 'Auth passed' })
})
这是中间件文件的内容。
function isAuth(req, res, next) {
const authorized = false
if (authorized) {
// User is authorized, call next
console.log('Auth passed...')
next()
} else {
// User is not authorized
res.status(401).send('You are not authorized to access this content')
}
}
function otherMiddleware(req, res, next) {
console.log('More MW operations..')
next()
}
module.exports = { isAuth, otherMiddleware }
更改为 module.exports = isAuth 或者如果我将 otherMiddleware 留在路由之外不会导致错误。
如果有人能告诉我哪里出了问题,我将不胜感激。
【问题讨论】:
-
如果不起作用,请告诉我们您是如何导入这些路由的。看来您可能没有正确导入它以匹配您导出它的方式。
-
@jfriend00 我以为就是这样。该模块使用的是
require,所以我将其更改为 `import { isAuth, otherMiddleware } from '../middleware/authMw.js'` 并确保它可以正常工作。现在错误是SyntaxError: Cannot use import statement outside a module。但是我尝试导入的文件本身使用了module.exports。我在这里错过了什么?谢谢!
标签: node.js express routes middleware