node.js在发出http请求时区分错误

我的node.js应用程序使用http.request到REST API http://army.gov/launch-nukes ,我需要区分三种可能的情况:

  • Success – 服务器答复肯定。 我知道我的敌人被毁灭了。
  • Failure – 我收到来自服务器的错误, 或者无法连接到服务器 。 我仍然有敌人。
  • Unknownbuild立到服务器的连接后 ,我发送了请求 – 但不知道发生了什么。 这可能意味着请求永远不会将其发送到服务器,或者服务器对我的响应从未做到。 我可能会也可能不会刚刚开始一场世界大战。

正如你所看到的,鉴别FailureUnknown情况对我来说是非常重要的,因为它们有着非常不同的后果和我需要采取的不同的行动。

我也非常喜欢使用http Keep-Alive,正如我能说的那样,我是一个战争贩子,并计划以连发的方式提出大量请求(然后长时间没有任何请求)

问题的核心是如何将连接错误/超时(这是一个Failure )与请求被置于连线(这是一个Unknown )之后发生的错误/超时分开。

在伪代码逻辑中,我想这样做:

 var tcp = openConnectionTo('army.gov') // start a new connection, or get an kept-alive one tcp.on('error', FAILURE_CASE); tcp.on('connectionEstablished', function (connection) { var req = connection.httpGetRequest('launch-nukes'); req.on('timeout', UNKNOWN_CASE); req.on('response', /* read server response and decide FAILURE OR SUCCESS */); } ) 

这里是一个例子:

 var http = require('http'); var options = { hostname: 'localhost', port: 7777, path: '/', method: 'GET' }; var req = http.request(options, function (res) { if (('' + req.statusCode).match(/^2\d\d$/)) { // Request handled, happy } else if (('' + req.statusCode).match(/^5\d\d$/)) // Server error, I have no idea what happend in the backend // but server at least returned correctly (in a HTTP protocol // sense) formatted response } }); req.on('error', function (e) { // General error, ie // - ECONNRESET - server closed the socket unexpectedly // - ECONNREFUSED - server did not listen // - HPE_INVALID_VERSION // - HPE_INVALID_STATUS // - ... (other HPE_* codes) - server returned garbage console.log(e); }); req.on('timeout', function () { // Timeout happend. Server received request, but not handled it // (ie doesn't send any response or it took to long). // You don't know what happend. // It will emit 'error' message as well (with ECONNRESET code). console.log('timeout'); req.abort(); }); req.setTimeout(5000); req.end(); 

我build议你使用netcat玩它,即:

 $ nc -l 7777 // Just listens and does not send any response (ie timeout) $ echo -e "HTTP/1.1 200 OK\n\n" | nc -l 7777 // HTTP 200 OK $ echo -e "HTTP/1.1 500 Internal\n\n" | nc -l 7777 // HTTP 500 

(等等…)

这通常在API状态码中。 在请求包中,您可以像这样访问它

 request('http://www.google.com', function (error, response, body) { if (!error && response.statusCode == 200) { console.log(body) // Print the google web page. } }) 

response.statusCode是200意味着它的工作。 500将是失败。 未知的将是从未被调用的callback。

如果您所描述的API不符合标准的响应代码,我不知道。 你必须看看文档。