首页 文章

发送响应后,如何结束Node / Express中的当前请求处理?

提问于
浏览
7

关于这个问题有一些帖子,但没有一个直接回答问题,正面 . 让我澄清一下,我理解(或者我认为)使用next(),next('route'),return next(),return以及它们对控制流的影响 . 我的应用程序的整个中间件包含一系列app.use,如:

app.use(f1);
 app.use(f2);
 app.use(f3);
 app.use(f4);
 ...

在每个中间件中,我都可以发送响应并完成,无需进一步处理 . 我的问题是我无法阻止处理进入下一个中间件 .

我有一个笨拙的工作 . 我只是在发送响应后设置了res.locals.completed标志 . 在所有中间件中,一开始,我检查此标志并跳过中间件中的处理(如果设置了标志) . 在第一个中间件中,此标志未设置 .

当然,必须有一个更好的解决方案,它是什么?我认为Express会隐式地通过一些特定于特定的方法来检查并跳过中间件吗?

1 回答

  • 7

    根据http://expressjs.com/guide/using-middleware.html的快递文件

    If the current middleware does not end the request-response cycle,
    it must call next() to pass control to the next middleware,
    otherwise the request will be left hanging.
    

    因此,如果中间件需要尽早结束请求 - 响应,只需不要调用 next() 但请确保中间件通过调用 res.endres.sendres.render 或任何隐含调用 res.end 的方法确实结束请求响应

    app.use(function (req, res, next) {
      if (/* stop here */) {
        res.end();
      } else {
        next();
      }
    });
    

    这是一个示例服务器,显示它的工作原理

    var express = require('express');
    var app = express();
    
    var count = 0;
    app.use(function(req, res, next) { 
      console.log('f1'); 
      next();
     })
    app.use(function(req, res, next) {
      console.log('f2');
      if (count > 1) {
        res.send('Bye');
      } else {
        next();
      }
    })
    app.use(function(req, res, next) {
      console.log('f3');
      count++;
      next();
    })
    
    app.get('/', function (req, res) {
      res.send('Hello World: ' + count);
    });
    
    var server = app.listen(3000);
    

    您将看到3个请求后,服务器显示“Bye”并且未到达f3

相关问题