2016-05-12 174 views
3

我的問題類似於這個問題:Node Js :is it possible to hit 1000 http get request to some api from a node js server但他們的油門解決方案並不適合我。Node.js https獲取請求ECONNRESET

我打電話給我們在Google App Engine上託管的api /網站,以觸發更新特定產品頁面的內存緩存的任務。從async.eachSeries調用此函數updateCache。該代碼是很簡單的:(這是一個消毒版)

function updateCache(object_name, callback) { 
    var options = { 
    host   : 'www.example.com', 
    path   : '/update-cache/' + object_name, 
    method  : 'GET', 
    agent   : false, 
    }; 
    var req = https.request(options, function(res) { 
    res.on('data', function() { 
     if (res.statusCode !== 200) { 
     console.log('successful'); 
     } 
    }); 
    res.on('end', function() { 
     console.log('end'); 
     callback(); 
    }); 
    }); 
    req.on('error', function(e) { 
    console.log('failed'); 
    console.error(e.stack); 
    callback(); 
    }); 
    req.end(); 
} 

它完美地運行我的Mac計算機上,但我需要的腳本使用的是Windows 7在Windows PC上運行,這就是被它得到這個錯誤:

events.js:141 
    throw er; // Unhandled 'error' event 
^

Error: read ECONNRESET 
    at exports._errnoException (util.js:870:11) 
    at TCP.onread (net.js:552:26) 
+0

你有沒有看到這個相關的帖子 - http://stackoverflow.com/questions/17245881/node-js-econnreset – ThisClark

+0

我實現了一個解決方案,我發現[stackoverflow](http ://stackoverflow.com/questions/19322248/node-js-distinguishing-errors-when-making-http-request)。到目前爲止,我的腳本一直運行良好。 –

+0

我一直在''req.on('timeout',...)中拋出錯誤,所以我跟着的代碼能夠捕獲錯誤,但我仍然不知道如何修復超時和連接關閉 –

回答

3

我跟着這個solution,它看起來是這樣的:

var req = https.request(options, function(res) { 
    res.on('data', function() { 
     if (res.statusCode !== 200) { 
      // HANDLE 
     } 
    }); 
    res.on('end', function() { 
     if (res.statusCode !== 200 && app.retry_count < 10) { 
      app.retry_count += 1; 
      retriggerFunction(param, callback); 
     } else { 
      app.retry_count = 0; 
      return callback(); 
     } 
    }); 
}); 
req.on('error', function(e) { 
    app.retry_count += 1; 
    retriggerFunction(param, callback); 
}); 
req.on('timeout', function(e) { 
    app.retry_count += 1; 
    retriggerFunction(param, callback); 
    req.abort(); 
}); 
req.on('uncaughtException', function(e) { 
    app.retry_count += 1; 
    retriggerFunction(param, callback); 
    req.abort(); 
}); 

retriggerFunction也只是我在這個包裹的功能它中林芽依不是「正確的」,但它目前正在爲我工​​作。如果有人有這方面的改進,請讓我知道