【问题标题】:Restify Middleware - correctly calling next middleware in stackRestify Middleware - 正确调用堆栈中的下一个中间件
【发布时间】:2013-05-08 19:13:50
【问题描述】:

我正在使用带有 Nodejs 的 Restify,我对将控制权返回到堆栈中的下一个中间件的正确方法有疑问。我希望当我说“堆栈中的下一个中间件”时使用的是正确的短语。

基本上,我的代码如下所示:

//server is the server created using Restify
server.use(function (req, res, next) {
    //if some checks are a success
    return next();
});

现在,我想知道代码应该是 return next(); 还是应该只是 next(); 以将控制权传递给堆栈中的下一个?

我检查过并且两者都工作 - 即两段代码都将成功通过控制并按预期返回数据 - 我想知道两者之间是否存在差异以及我是否需要使用另一个。

【问题讨论】:

    标签: node.js restify


    【解决方案1】:

    没有区别。我看了一下 Restify 源码,它似乎根本没有对中间件的返回值做任何事情。

    之所以使用return next(),纯粹是为了方便:

    // using this...
    if (someCondition) {
      return next();
    }
    res.send(...);
    
    // instead of...
    if (someCondition) {
      next();
    } else {
      res.send(...);
    };
    

    这可能有助于防止这样的错误:

    if (someCondition) 
      next();
    res.send(...); // !!! oops! we already called the next middleware *and* we're 
                   //     sending a response ourselves!
    

    【讨论】:

    • 你好,你能回复我What doing next callback in http handlers? server.get('/', function(req,res,next){res.end();})下一个电话吗?
    • @vp_arth 如果您没有通过以一种或另一种方式发回响应来结束请求,您可以使用next() 将控制权传递给下一个路由/中间件/(error-)handler
    猜你喜欢
    • 1970-01-01
    • 2013-09-07
    • 2021-03-03
    • 2010-10-10
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多