Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop Express.js route from next()?

I have a weird situation...

I have a Express.js, Node.js and Mongoose web app.

One of the routes has a mongoose callback that calls respond.send(...). However, because there is nothing else after the callback, I suspect it goes to next() route automatically.

Ex:

//getItem 
app.get('/api/ItemOne', isUserValid, routes.getItem); 
//getAnotherItem
app.get('/api/getAnotherItem', isUserValid, routes.getAnotherItem);

//Routes
exports.getItem = function (req, res) {
  //console.log ('In getItem'); 
   getItem .findOne({ some_id : some_id}, function(err, getItem ){
      //console.log ('In getItem callback');
      res.send({
         itemName : getItem .itemName,
         itemValue : getItem .itemValue;
      });
   })
});

exports.getAnotherItem = function (req, res) { 
   //console.log ('In getAnotherItem');
   getAnotherItem.findOne({ some_id : some_id}, function(err, getAnotherItemRet){
      //console.log ('In getAnotherItem Callback');
      res.send({
         itemName : getAnotherItemRet.itemName,
         itemValue : getAnotherItemRet.itemValue;
      });
   })
});

I get the following sequence of messages on the console...

In getItem
In getAnotherItem
In getItem callback
In getAnotherItem callback

I am assuming because the route does not finish, it calls next() automatically.

Q: How do I prevent the second route from being called automatically.

like image 498
Ram Iyer Avatar asked Apr 21 '13 18:04

Ram Iyer


2 Answers

Try reversing req and res:

// wrong
exports.getItem = function (res, req) {
// right
exports.getItem = function (req, res) {

(and same for getAnotherItem).

like image 191
robertklep Avatar answered Sep 22 '22 19:09

robertklep


In order to understand why you get messages in that order, we need to know what url are you calling to generate that message.

In any case though, "/api/getItem" does not call "/api/getAnotherItem" for two reasons:

  1. if you call next in "/api/getItem", it will call the next matching route, in this case, it will match either a route on "/api", "/" or nothing at all. the next() function basically calls the route's "parent".
  2. Next() must be called explicitly, if you do not return an answer, express will simply wait indefinitely until res.send is called (which is how it can handle async functions).

It's possible you have some kind of middleware (I.E. used with app.use and not app.get) which could call something like that, but most likely, you are calling both urls at the same time somehow.

like image 45
Alon Bar David Avatar answered Sep 25 '22 19:09

Alon Bar David