Express.js响应超时 [英] Express.js Response Timeout

查看:671
本文介绍了Express.js响应超时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题

我一直在寻找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){});

FIX

我在 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();
}

如果您计划使用超时中间件作为上述顶级中间件, 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆