关于这个问题有一些帖子,但没有一个直接、正面地回答这个问题。让我澄清一下,我理解(或者我认为)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 上的 express 文档
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 真正结束请求-响应
、res.send
、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
关于node.js - 发送响应后,Node/Express 中如何结束当前的请求处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33648905/