"Error: Route.get() requires a callback function but got a [object Undefined]" when doing multiple exporting
"Error: Route.get() requires a callback function but got a [object Undefined]" when doing multiple exporting
我正在尝试导出中间件功能,以便其他 类 可以调用它。
我做了一些 google 搜索,但对我的情况不起作用。
这是代码
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
不再是您分配的新导出对象的 属性。您可以翻转顺序:
module.exports = app => {
};
module.exports.isLoggedIn = isLoggedIn;
这样,你先定义一个新的module.exports
对象(刚好是一个函数对象),然后给新对象添加一个属性。
我正在尝试导出中间件功能,以便其他 类 可以调用它。
我做了一些 google 搜索,但对我的情况不起作用。
这是代码
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
不再是您分配的新导出对象的 属性。您可以翻转顺序:
module.exports = app => {
};
module.exports.isLoggedIn = isLoggedIn;
这样,你先定义一个新的module.exports
对象(刚好是一个函数对象),然后给新对象添加一个属性。