Node.js:某个时间的并行GET请求出现未处理的错误

Node.js : Unhandled error on parallel GET requests on a certain time

本文关键字:请求 未处理 错误 GET 并行 时间 Node js      更新时间:2023-09-26

我正在使用请求/请求模块向API发送大约100个并行GET请求。我遇到的问题是关于80th to 100th request的随机问题,node抛出了这个异常:

events.js:141
      throw er; // Unhandled 'error' event
      ^
Error: connect ETIMEDOUT 0.0.0.0:80 //a dummy ip
    at Object.exports._errnoException (util.js:860:11)
    at exports._exceptionWithHostPort (util.js:883:20)
    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)

以下是我的请求默认值:

var apiRequest = request.defaults({
    url : url, //response is in xml format
    headers : {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
        'Accept-Language': 'en-US,en;q=0.8'
    },
    method : 'GET',
    gzip : true,
    encoding : 'utf8',
    pool: {maxSockets: Infinity},
    forever : true,
    timeout : 120000
});

此外,我请求在数组上使用循环

通过递归地请求失败的URL on error event直到没有超时为止,修复了我的问题:

function getAPI(url) {
    var apiRequest = request.defaults({
        url : url,
        headers : {
            'Accept': 'text/html,application/xhtml+xml,application/xml'
        },
        method : 'GET',
        gzip : true
    });
    apiRequest(function (error, response, body) {
    }).on('error', function(e){
        getAPI(this.uri.href);//this is important
    }).end();
}