对快速路由使用回调函数时的未定义参数

Undefined Argument when using Callback function for express route

本文关键字:函数 未定义 参数 回调 路由      更新时间:2023-09-26

目前,我在Express中使用了许多路线。有些路线可能相当长。常见路由如下所示:

router.get('/api/comments', function(req, res, next){
  Comment.find({"user": req.payload._id}).exec(function(err,comments){
    if(err){return next(err); }
    res.json(comments);
  })
}

这工作正常。但是我多次调用路由,可能会很长。所以我正在尝试创建一个可以被各种路由调用的回调函数。例如

var testFunction = function(req, res, next){
  Comment.find({"user": req.payload._id}).exec(function(err,comments){
    if(err){return next(err); }
    res.json(comments);
  })
}
router.get('/api/comments', testFunction(req,res,next)); 

但是,我总是会在最后一行收到"未定义 req"错误。只是想知道我在这里做错了什么?

router将函数作为参数,而不是执行该函数的结果。

router.get('/api/comments', testFunction);会起作用。

尝试执行router.get('/api/comments', testFunction);而不是router.get('/api/comments', function(req, res, next)