简体   繁体   English

节点http.ClientRequest不会触发“错误”事件

[英]Node http.ClientRequest does not fire “error” event

I have the following javascript node.js code: 我有以下javascript node.js代码:

    var options = {
         host: "x.y.z"
        ,path: "/api/abc/"
        ,method: "GET"
    };

    var req = http.request(options);

   req.on('response' , function(data) {
      console.log("response: ",data.statusCode);
      done();
   });

   req.on('error' , function() {
      console.log("error");
      done();
   });

   req.end();

I can't get the error event when an actual HTTP request error occurs. 当发生实际的HTTP请求错误时,我无法收到error事件。 What am I missing ? 我想念什么?


Preliminary findings: It would appear that the failure case "no response from server" (eg due to network issue) does not fire any event. 初步发现:似乎失败案例“服务器未响应”(例如由于网络问题)不会引发任何事件。 So, the workaround is to create a 'timer' and trap this condition by yourself. 因此,解决方法是创建一个“计时器”并自己捕获此条件。

Try using an if / else statement instead of two independent functions. 尝试使用if / else语句代替两个独立的函数。

if(response you want && response.statusCode = 200){
   //logic
} else {
   //console.log("error")
}

You should create your own Timeout function inside the request. 您应该在请求中创建自己的Timeout函数。 In fact, I believe that after a lot of time (maybe a minute?) the request would fail. 实际上,我认为经过很多时间(也许是一分钟?)后,请求将失败。 But, if you require something more earlier, you can check this thread that asks for the same thing: 但是,如果您需要更早的功能,则可以检查该线程是否要求相同的内容:

How to set a timeout on a http.request() in Node? 如何在Node中的http.request()上设置超时?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM