【问题标题】:How to stop Express.js route from next()?如何从 next() 停止 Express.js 路由?
【发布时间】:2013-04-22 07:03:46
【问题描述】:

我的情况很奇怪……

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

其中一个路由有一个调用 respond.send(...) 的 mongoose 回调。但是,由于回调之后没有其他内容,我怀疑它会自动转到 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()。

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

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    尝试反转reqres

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

    getAnotherItem 也一样)。

    【讨论】:

    • 我很抱歉 - 它是 (req, res)。为简单起见,在我在这里提出问题之前,我编辑了代码并意外地反转了它。我已经编辑了上面的问题。感谢您指出。
    【解决方案2】:

    为了了解您为何按此顺序接收消息,我们需要知道您调用哪个 url 来生成该消息。

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

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

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

    【讨论】:

    • 谢谢伊尔尼亚尔。很好……我实际上同时调用了两个网址。我重新排列了代码并开始看到这个问题。因此假设这是路线的问题。
    猜你喜欢
    • 2018-02-18
    • 1970-01-01
    • 2011-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-02
    • 2018-06-10
    相关资源
    最近更新 更多