Nodejs http在超时或错误时重试

nwa*_*arp 12 http node.js

我试图在超时或错误时自动重试HTTP请求.
目前我的代码如下所示:

var req = http.get(url, doStuff)
              .on('error', retry)
              .setTimeout(10000, retry);
Run Code Online (Sandbox Code Playgroud)

但是,单个请求有时可以触发"on error"和"timeout"事件.实施重试的更好方法是什么?

Gag*_*gan 23

我一直在寻找同样的事情,发现更有趣的模块requestretry,非常适合这种要求.

这是用法:

var request = require('requestretry')

request({
  url: myURL,
  json: true,
  maxAttempts: 5,  // (default) try 5 times 
  retryDelay: 5000, // (default) wait for 5s before trying again
  retrySrategy: request.RetryStrategies.HTTPOrNetworkError // (default) retry on 5xx or network errors
}, function(err, response, body){
  // this callback will only be called when the request succeeded or after maxAttempts or on error 
  if (response) {
    console.log('The number of request attempts: ' + response.attempts);
  }
})
Run Code Online (Sandbox Code Playgroud)

  • @Holf 不知道,我只是回答,因为我认为这个模块是所提到的问题的完美解决方案。我使用了该模块,它运行良好。 (2认同)

msc*_*dex 6

你可以尝试这样的事情:

function doRequest(url, callback) {
  var timer,
      req,
      sawResponse = false;
  req = http.get(url, callback)
            .on('error', function(err) {
              clearTimeout(timer);
              req.abort();
              // prevent multiple execution of `callback` if error after
              // response
              if (!sawResponse)
                doRequest(url, callback);
            }).on('socket', function(sock) {
              timer = setTimeout(function() {
                req.abort();
                doRequest(url, callback);
              }, 10000);
            }).once('response', function(res) {
              sawResponse = true;
              clearTimeout(timer);
            });
}
Run Code Online (Sandbox Code Playgroud)

更新:在最近/现代版本的节点中,您现在可以指定一个timeout选项(以毫秒为单位),用于设置套接字超时(在连接套接字之前).例如:

http.get({
 host: 'example.org',
 path: '/foo',
 timeout: 5000
}, (res) => {
  // ...
});
Run Code Online (Sandbox Code Playgroud)