Sydney Sydney - 4 months ago 7
Javascript Question

Undefined Argument when using Callback function for express route

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?

Answer

router takes a function as argument not the result of executing that function.

router.get('/api/comments', testFunction); will work.

Comments