如何从next()停止Express.js路由?

时间:2013-04-21 18:09:14

标签: node.js express mongoose

我有一种奇怪的情况......

我有一个Express.js,Node.js和Mongoose网络应用程序。

其中一条路由有一个调用respond.send(...)的猫鼬回调。但是,因为回调后没有别的东西,我怀疑它会自动转到next()路由。

例如:

//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;
      });
   })
});

我在控制台上收到以下消息序列......

In getItem
In getAnotherItem
In getItem callback
In getAnotherItem callback

我假设因为路线没有完成,它会自动调用next()。

问:如何防止自动调用第二条路线。

2 个答案:

答案 0 :(得分:4)

尝试撤消reqres

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

(和getAnotherItem相同)。

答案 1 :(得分:2)

为了理解您为什么按顺序获取消息,我们需要知道您要调用哪个URL来生成该消息。

无论如何,“/ api / getItem”没有调用“/ api / getAnotherItem”有两个原因:

  1. 如果您在“/ api / getItem”中调用next,它将调用下一个匹配的路由,在这种情况下,它将匹配“/ api”,“/”上的路由或者根本不匹配。 next()函数基本上调用路由的“父”。
  2. 必须显式调用Next(),如果不返回答案,express将无限期地等待,直到调用res.send(这是它如何处理异步函数)。
  3. 你可能有某种中间件(I.E.与app.use一起使用而不是app.get)可以调用类似的东西,但最有可能的是,你在某种程度上同时调用这两个URL。