我想知道在使用express时,默认的HTTP请求超时时间是多少。
我的意思是:当浏览器或服务器没有手动关闭连接时,经过多少秒处理http请求后,Express/Node.js服务器会关闭连接?
如何为单个路由更改此超时时间? 我想在一个特殊的音频转换路由中将其设置为约15分钟。
非常感谢。
汤姆
我想知道在使用express时,默认的HTTP请求超时时间是多少。
我的意思是:当浏览器或服务器没有手动关闭连接时,经过多少秒处理http请求后,Express/Node.js服务器会关闭连接?
如何为单个路由更改此超时时间? 我想在一个特殊的音频转换路由中将其设置为约15分钟。
非常感谢。
汤姆
req.connection.setTimeout(ms);
看起来是在Node.js中设置HTTP服务器请求超时的方法。
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();
};
}
app.get('/longendpoint', function (req, res) {
req.setTimeout(360000); // 5 minutes
...
});
connect-timeout 或其他通常不起作用。 总是可以通过在 nginx 域名/子域名级别设置超时时间来解决:
location / {
proxy_read_timeout 300;
proxy_connect_timeout 300;
proxy_send_timeout 300;
proxy_pass http://xxxx:3009;
}