簡體   English   中英

“錯誤:Route.get() 需要回調 function 但得到 [object Undefined]” 進行多次導出時

[英]“Error: Route.get() requires a callback function but got a [object Undefined]” when doing multiple exporting

我正在嘗試導出中間件 function 以便其他類可以調用它。

我做了一些谷歌搜索,但對我的情況不起作用。

這是代碼

auth.js

isLoggedIn = (req, res, next) => {
  next();
}

module.exports.isLoggedIn = isLoggedIn;

module.exports = app => {
};

profile.js

const isLoggedIn = require('./auth').isLoggedIn;
let profile = [];
getAllProfile = (req, res) => {
    res.send(profile);
}

module.exports = (app) => {
    app.get('/all-profile',isLoggedIn, getAllProfile);

}

index.js

const express = require("express");
const bodyParser = require("body-parser");

const app = express();
app.use(bodyParser.json());

const port = process.env.PORT || 3000;
const server = app.listen(port, () => {
  const addr = server.address();
  console.log(`Server listening at ${port}`);
});


let auth = require("./src/auth");
auth(app);

let profile = require("./src/profile");
profile(app);

錯誤信息是

\node_modules\express\lib\router\route.js:202
        throw new Error(msg);
        ^

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

我在這里做錯了什么?

你在這里用第二行覆蓋你的module.exports

module.exports.isLoggedIn = isLoggedIn;

module.exports = app => {
};

因此.isLoggedIn不再是您分配的新導出 object 的屬性。 您可以翻轉訂單:

module.exports = app => {
};

module.exports.isLoggedIn = isLoggedIn;

這樣,您首先定義一個新module.exports object(恰好是一個 function 對象),然后向新的 object 添加一個屬性。

暫無
暫無

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

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