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

Ram*_*yer 5 mongoose node.js express

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

我有 Express.js、Node.js 和 Mongoose Web 应用程序。

其中一条路由有一个调用 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;
      });
   })
});
Run Code Online (Sandbox Code Playgroud)

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

In getItem
In getAnotherItem
In getItem callback
In getAnotherItem callback
Run Code Online (Sandbox Code Playgroud)

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

Q:如何防止第二条路由被自动调用?

小智 2

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

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

  1. 如果您在“/api/getItem”中调用 next,它将调用下一个匹配的路由,在这种情况下,它将匹配“/api”、“/”上的路由或根本不匹配。next() 函数基本上调用路由的“父级”。
  2. Next() 必须显式调用,如果不返回答案,express 将无限期地等待,直到调用 res.send (这就是它处理异步函数的方式)。

您可能有某种中间件(IE 与 app.use 一起使用,而不是与 app.get 一起使用)可以调用类似的东西,但最有可能的是,您以某种方式同时调用两个网址。