node.js请求中的超时
我不知道node.js request
模块如何在timeout
参数方面工作。node.js请求中的超时
timeout
时间过后会发生什么?即:
var request = require('request');
var options = {
url: Theurl,
timeout: 300000
};
request(options, function(error, resp, body) {...
300000
后会发生什么?请求是否尝试再次请求网址?
我还发现,Linux Kernel
有一个默认的20秒TCP socket connection timeout.
(http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout) 这是否意味着在request
timeout
选项将最多20秒(如果我不改变),无论我在options
设置?我使用Ubuntu
。
从请求包的自述:
Note that if the underlying TCP connection cannot be established,
the OS-wide TCP connection timeout will overrule the timeout option
所以你的情况,请求将被中止后的20秒。该请求不会尝试再次请求URL(即使超时设置为低于20000的值)。您必须为此编写自己的逻辑或使用其他程序包,例如requestretry。
例子:
var options = {
url: 'http://www.gooooerererere.com/',
timeout: 5000
}
var maxRequests = 5;
function requestWithTimeout(attempt){
request(options, function(error,response,body){
if(error){
console.log(error);
if(attempt==maxRequests)
return;
else
requestWithTimeout(attempt+1);
}
else {
//do something with result
}
});
}
requestWithTimeout(1);
您还可以检查特定的错误信息,如ETIMEDOUT,与
if(error.code == [ERROR_MESSAGE])
如果发生超时,你的回调函数会被错误执行的设定信息'错误:ETIMEDOUT'。
这个小项目https://github.com/FGRibreau/node-request-retry提供了随时可用的配置包装,使重试由许多连接错误代码触发,包括超时。
好吧,是否有可能重试,直到'request'成功? – user1665355
看看这个项目:[链接](https://github.com/FGRibreau/node-request-retry)。它是一个请求包装器,在最终放弃之前配置重试延迟和重试次数。 –
谢谢!将退房 – user1665355
好的,谢谢,但你怎么说赖特我自己的逻辑? – user1665355
您可以等待错误(请求超时)并再次进行呼叫。让我知道你是否需要一个例子。 – piscator
好的。是的,请举个例子,它会很亲切!然后我可以接受它作为答案。 – user1665355