首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >node.js在发出http请求时区分错误

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

Stack Overflow用户
提问于 2013-10-11 23:48:50
回答 1查看 34.8K关注 0票数 28

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

  • Success --服务器的回答是肯定的。我知道我的敌人是destroyed.
  • Failure --我收到了来自服务器的错误,或者无法连接到服务器。我还有敌人。
  • Unknown --建立到服务器的连接后,我发送了请求--但不确定发生了什么。这可能意味着请求从未到达服务器,或者服务器对我的响应从未到达。我可能刚刚开始了一场世界大战,也可能不是。--

正如您所看到的,区分FailureUnknown的情况对我来说非常重要,因为它们具有非常不同的后果和我需要采取的不同操作。

我也非常喜欢使用http Keep-Alive --我能说什么呢,我有点像个战争贩子,计划突然发出很多请求(然后在很长一段时间内什么都不做)

--

问题的核心是如何将连接错误/超时(即Failure)与请求发送到网络(即Unknown)后发生的错误/超时分开。

在psuedo-code逻辑中,我希望这样:

代码语言:javascript
复制
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 */);
   }
)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-10-12 17:12:43

下面是一个示例:

代码语言:javascript
复制
var http = require('http');

var options = {
  hostname: 'localhost',
  port: 7777,
  path: '/',
  method: 'GET'
};

var req = http.request(options, function (res) {
  // check the returned response code
  if (('' + res.statusCode).match(/^2\d\d$/)) {
    // Request handled, happy
  } else if (('' + res.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, i.e.
  //  - 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
  // (i.e. 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();

我建议你使用netcat来使用它,即:

代码语言:javascript
复制
$ nc -l 7777
// Just listens and does not send any response (i.e. 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

(以此类推...)

票数 40
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19322248

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档