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

在这个问题上有几个post,但没有直接回答这个问题,正面。 让我澄清,我明白(或者我认为)使用next(),next('route'),return next(),返回以及它们对控制stream的影响。 我的整个应用程序中间件由一系列的app.use组成,如下所示:

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

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

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

当然,必须有更好的解决办法,那是什么? 我认为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.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个请求后,服务器显示“再见”,没有达到f3