Reputation: 1439
Currently, I am using many routes in Express. Some of the routes can be quite lengthy. A common route look like the following:
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);
})
}
This works fine. But I am calling routes multiple times and it can be quite lengthy. So I am trying to create a callback function which can be invoked by the various routes. E.g.
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));
However, I will always get a "req is not defined" error on the last line. Just wondering what I am doing wrong here?
Upvotes: 2
Views: 57
Reputation: 210
Try doing router.get('/api/comments', testFunction);
instead of router.get('/api/comments', function(req, res, next)
Upvotes: 1
Reputation: 4037
router
takes a function as argument not the result of executing that function.
router.get('/api/comments', testFunction);
will work.
Upvotes: 1