簡體   English   中英

無法使用 module.export 導出多個 function

[英]Cannot export more than one function using module.export

當我嘗試啟動我的 Node/Express 應用程序時出現以下錯誤。 該問題似乎是由使用module.exports從同一文件導出多個函數引起的。 也就是說,應用程序啟動正常,路由中間件僅在我導出單個 function 時才工作。

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留在路由之外不會導致錯誤。

如果有人能告訴我哪里出了問題,我將不勝感激。

您沒有向我們展示導入代碼,所以錯誤是導入代碼與導出代碼不匹配,因此您最終得到的中間件是 object 而不是中間件 function。

如果您像這樣導出:

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 object,而不是你的中間件,因此它不會是 function,你會得到這個錯誤:

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

該特定錯誤意味着您將 object 而不是 function 傳遞給.get() 因此,您的導出中的某些內容與您導入的方式不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM