Express.js HTTP请求超时

11

我想知道在使用express时,默认的HTTP请求超时时间是多少。

我的意思是:当浏览器或服务器没有手动关闭连接时,经过多少秒处理http请求后,Express/Node.js服务器会关闭连接?

如何为单个路由更改此超时时间? 我想在一个特殊的音频转换路由中将其设置为约15分钟。

非常感谢。

汤姆

4个回答

7

req.connection.setTimeout(ms); 看起来是在Node.js中设置HTTP服务器请求超时的方法。


3
这会设置连接超时而不是请求超时。 - kilianc

5

req.connection.setTimeout(ms);可能不是一个好主意,因为多个请求可以通过同一套接字发送。

试试connect-timeout或者使用以下方法:

var errors = require('./errors');
const DEFAULT_TIMEOUT = 10000;
const DEFAULT_UPLOAD_TIMEOUT = 2 * 60 * 1000;

/*
Throws an error after the specified request timeout elapses.

Options include:
    - timeout
    - uploadTimeout
    - errorPrototype (the type of Error to throw)
*/
module.exports = function(options) {
    //Set options
    options = options || {};
    if(options.timeout == null)
        options.timeout = DEFAULT_TIMEOUT;
    if(options.uploadTimeout == null)
        options.uploadTimeout = DEFAULT_UPLOAD_TIMEOUT;
    return function(req, res, next) {
        //timeout is the timeout timeout for this request
        var tid, timeout = req.is('multipart/form-data') ? options.uploadTimeout : options.timeout;
        //Add setTimeout and clearTimeout functions
        req.setTimeout = function(newTimeout) {
            if(newTimeout != null)
                timeout = newTimeout; //Reset the timeout for this request
            req.clearTimeout();
            tid = setTimeout(function() {
                if(options.throwError && !res.finished)
                {
                    //throw the error
                    var proto = options.error == null ? Error : options.error;
                    next(new proto("Timeout " + req.method + " " + req.url) );
                }
            }, timeout);
        };
        req.clearTimeout = function() {
            clearTimeout(tid);
        };
        req.getTimeout = function() {
            return timeout;
        };
        //proxy end to clear the timeout
        var oldEnd = res.end;
        res.end = function() {
            req.clearTimeout();
            res.end = oldEnd;
            return res.end.apply(res, arguments);
        }
        //start the timer
        req.setTimeout();
        next();
    };
}

5
默认的请求超时时间在 Node v0.9+ 版本中为2分钟。这是express使用的时间。
您可以使用以下方法增加单个路由的超时时间:
app.get('/longendpoint', function (req, res) {
   req.setTimeout(360000); // 5 minutes
   ...
});

似乎Node 13将默认请求超时时间更改为0秒。 - VocoJax

0

connect-timeout 或其他通常不起作用。 总是可以通过在 nginx 域名/子域名级别设置超时时间来解决:

location / {

                proxy_read_timeout 300;
                proxy_connect_timeout 300;
                proxy_send_timeout 300; 
   
            proxy_pass http://xxxx:3009;
        }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接