【问题标题】:Cannot export more than one function using module.export无法使用 module.export 导出多个函数
【发布时间】: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


【解决方案1】:

您没有向我们展示导入代码,所以错误是导入代码与导出代码不匹配,因此您最终得到的是中间件对象而不是中间件函数。

如果您像这样导出:

module.exports = { isAuth, otherMiddleware };

然后,这就是您导入的方式:

const MW = require("./middleware.js");

router.get('/check', MW.isAuth, MW.otherMiddleware, function (req, res) {
     res.send({ messsage: 'Auth passed' })
});

或者,您可以像这样使用解构赋值:

const { isAuth, otherMiddlware } = require("./middleware.js");

router.get('/check', isAuth, otherMiddleware, function (req, res) {
     res.send({ messsage: 'Auth passed' })
});

你得到的具体错误看起来就像你在做这样的事情:

const isAuth = require("./middleware.js");

这会给你 module.exports 对象,而不是你的中间件,因此它不是一个函数,你会得到这个错误:

Error: Route.get() requires a callback function but got a [object Object]

该特定错误意味着您将一个对象而不是函数传递给.get()。因此,您的导出中的某些内容与您导入的方式不匹配。

【讨论】:

    猜你喜欢
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 2020-09-12
    • 1970-01-01
    • 2020-12-28
    相关资源
    最近更新 更多