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

Sun*_*nny 8 middleware node.js express

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

 app.use(f1);
 app.use(f2);
 app.use(f3);
 app.use(f4);
 ...
Run Code Online (Sandbox Code Playgroud)

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

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

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

Jer*_*NER 8

根据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.
Run Code Online (Sandbox Code Playgroud)

所以,如果一个中间件需要提前结束请求-响应,根本不叫next(),但要确保中间件真正结束通过调用请求-响应res.end,res.send,res.render即隐含来电或任何方法res.end

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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