Express.js 响应超时 [英] Express.js Response Timeout
问题描述
问题
我一直在寻找 Express.js 的请求/响应超时,但似乎一切都与连接有关,而不是请求/响应本身.
I've been looking for request/response timeouts for Express.js but everything seems to be related to the connection rather than the request/response itself.
如果一个请求需要很长时间,它应该超时.显然这不应该发生,但即使是一个简单的错误,例如没有调用回调或没有 res.send()
的路由处理程序,浏览器将永远等待回复.
If a request is taking a long time, it should be timed out. Obviously this shouldn't happen but even a simple mistake as having a route handler without a call to the callback or without res.send()
, the browser will keep waiting for a reply forever.
空路由处理程序就是一个完美的例子.
An empty route handler is a perfect example of this.
app.get('/sessions/', function(req, res, callback){});
修复
我在之前 app.use(app,router);
添加了以下内容,它似乎添加了超时功能.有没有人对此有任何经验/意见?
I added the following before app.use(app,router);
and it seemed to add the timeout functionality. Does anyone have any experience/opinion on this?
app.use(function(req, res, next){
res.setTimeout(120000, function(){
console.log('Request has timed out.');
res.send(408);
});
next();
});
请注意,我已将超时设置为 2 分钟.
Note that I've set the timeout to 2 minutes.
推荐答案
已经有一个支持超时的连接中间件:
There is already a Connect Middleware for Timeout support:
var timeout = express.timeout // express v3 and below
var timeout = require('connect-timeout'); //express v4
app.use(timeout(120000));
app.use(haltOnTimedout);
function haltOnTimedout(req, res, next){
if (!req.timedout) next();
}
如果您打算像上面一样使用 Timeout 中间件作为顶级中间件,haltOnTimedOut
中间件需要是堆栈中定义的最后一个中间件,用于捕获超时事件.感谢@Aichholzer 的更新.
If you plan on using the Timeout middleware as a top-level middleware like above, the haltOnTimedOut
middleware needs to be the last middleware defined in the stack and is used for catching the timeout event. Thanks @Aichholzer for the update.
请记住,如果您推出自己的超时中间件,4xx 状态代码用于客户端错误,5xx 用于服务器错误.408 保留用于以下情况:
Keep in mind that if you roll your own timeout middleware, 4xx status codes are for client errors and 5xx are for server errors. 408s are reserved for when:
在服务器准备等待的时间内,客户端没有产生请求.客户端可以在以后的任何时间不加修改地重复请求.
The client did not produce a request within the time that the server was prepared to wait. The client MAY repeat the request without modifications at any later time.
这篇关于Express.js 响应超时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!