[英]Error: Route.get() requires a callback function but got a [object Undefined] while using imported function
I am checking if a user is logged in a route called forum.我正在检查用户是否登录了名为论坛的路线。 I am importing it like this.
我正在像这样导入它。 The file is routes/forum.js
该文件是 routes/forum.js
const isloggedinimport = require('../index')
I have the function on index.js我在 index.js 上有 function
const isloggedin = (req,res,next) => {
if(req.user) {
next()
}
else {
res.render('loginerror',)
}
}
I am exporting with我正在出口
module.exports = isloggedin
When I try to run this当我尝试运行它时
router.get('/', isloggedinimport.isloggedin, (req, res) => {
res.render('monitors/monitorhome')
});
module.exports = router
I get the error that Route.get() requires a callback function but got a [object Undefined]我收到 Route.get() 需要回调 function 但得到 [object Undefined] 的错误
The error is on this line错误在这一行
router.get('/', isloggedinimport.isloggedin, (req, res) => {
How do I fix this?我该如何解决?
When exporting the function, try using the following code:导出 function 时,尝试使用以下代码:
module.exports.isloggedin = isloggedin
This will set the property isloggedin
to the function so that when you call isloggedinimport.isloggedin
, it will access the function properly.这会将属性
isloggedin
设置为 function 以便当您调用isloggedinimport.isloggedin
时,它将正确访问 function。 Alternatively, you could use the following code to export your function:或者,您可以使用以下代码导出您的 function:
module.exports = isloggedin
and then use this code to import the function:然后使用此代码导入 function:
const isloggedin = require('../index')
...
router.get('/', isloggedin, (req, res) => {
res.render('monitors/monitorhome')
});
Had the same problem and fixed it by adding brackets around the function you want to export:有同样的问题,并通过在要导出的 function 周围添加括号来修复它:
module.exports = {isloggedin};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.