Yaki Klein
Yaki Klein

Reputation: 4376

call function object from route in express js

My code looks something like this:

router.route('/user')
.post(function(req, res, next){

 queryDB(arg1, arg2, prepareRes)

})
.get(function(req, res, next){

queryDB(arg3, arg4, prepareRes)    

});

var prepareRes = function(err, data){

    if(err) next(err);
    else{
        req.data = data;
    }
};

when i run this code i get the following error:

ReferenceError: next is not defined

or

ReferenceError: req is not defined

This happens because req and next ,are outside prepareRes scope.

How can get around this ERROR??

I don't want to have to duplicate the same lines of code in both routes and its not possible to use

route.all

in my case.

Upvotes: 1

Views: 9907

Answers (2)

Robert Moskal
Robert Moskal

Reputation: 22553

prepareRes is declared outside of the post and get handlers so it has no access to the req(uest) or next.

The most obvious solution is to add request and next parameters to the prepareRes function signature and then, when calling prepareRes in the request handlers, to wrap the call in an anonymous function that can access them:

router.route('/user')
.post(function(req, res, next){

    queryDB(arg1, arg2, function(err, data){

        prepareRes(err,data, req, next);
    })

})
.get(function(req, res, next){

    queryDB(arg3, arg4, function(err, data){

        prepareRes(err,data, req, next);
    })

});

var prepareRes = function(err, data, req, next){

if(err) next(err);
else{
    req.data = data;
}
};

Using something like lodash you you could get rid of the anonymous functions and partially apply the additional arguments like so:

queryDB(arg1, arg2, _.partialRight(prepareRes, res, next));

But you still have to change the prepareRes signature.

Upvotes: 1

David Karlsson
David Karlsson

Reputation: 9696

since prepareRes is not inside of any of the above functions, where req,res are provided it can not find req on its namespace, assuming req and next are not globals.

Here for instance: req and next are passed to an error handler function:

function clientErrorHandler(err, req, res, next) {
  if (req.xhr) {
    res.status(500).send({ error: 'Something blew up!' });
  } else {
    next(err);
  }
}

Then next and res is available in the scope.

Upvotes: 0

Related Questions