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

After sending response, how to end the current request processing in Node/Express?

有一些帖子讨论了这个问题,但是 none 直接正面地回答了这个问题。让我澄清一下,我理解(或者我认为)next()、next('route')、return next()、return 的使用及其对控制流的影响。 我的应用程序的整个中间件由一系列 app.use 组成,如:

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

在这些中间件中的每一个中,我都有可能发送响应并在不需要进一步处理的情况下完成。我的问题是我无法停止处理转到下一个中​​间件。

我有一个笨拙的解决方法。我只是在发送响应后设置了一个 res.locals.completed 标志。在所有中间件中,一开始,我检查这个标志,如果设置了标志,则跳过中间件中的处理。在第一个中间件中,此标志未设置。

当然,一定有更好的解决办法,是什么?我认为 Express 会隐式地进行此检查并通过某些特定于 express 的方法跳过中间件?

根据 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.end、[=15真正结束请求-响应=]、res.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