https.get()使用events.js运行https.request()超时:136 throw er; //未处理的错误'事件

时间:2018-03-15 13:33:13

标签: node.js httprequest

在下面的示例中,我试图调用测试REST api:api.postcodes.io。使用https.get()的函数工作正常,使用https.request()的函数挂起然后超时。这有点奇怪。

有谁知道可能会发生什么?我尝试过使用https.request()的各种方法,但它们的行为方式相同。示例代码:

changeAnnotation(csvColumn, "name", "newName")

程序的控制台输出如下:

    "use strict";
//
// This is a working example of https.get()
//
const https = require("https");

function https_get()
{
    console.log("https_get()");
    const url = "https://api.postcodes.io/postcodes/BL34HG";
    https.get(url, res => {
      res.setEncoding("utf8");
      let body = "";
      res.on("data", data => {
        body += data;
      });
      res.on("end", () => {
        body = JSON.parse(body);
        console.log(body);

      });
    });
}

// This doesn't work. 
function https_request()
{
    console.log("https_request()");
    var headers= {
            "Content-Type": "application/json"
        };
    var options = {
            "method": "GET",
            "host": "api.postcodes.io",     // Don't include https:// as throws an error
            "path": "/postcodes/SW1A1AA",
            "headers": headers
    };

    console.log("-------------------------------")
    console.log("failed request options:",options); 
    console.log("-------------------------------")

    https.request(options, res => {

        if (res.statusCode != 200) {
            console.log("\tHTTPS statuscode not 200: ",res.statusCode);
            callback(false);
            return;
        }
        console.log("res.StatusCode:", res.StatusCode);
        res.setEncoding("utf8");
        let body = "";

        res.on("data", data => {
          body += data;
        });

        res.on("end", () => {
          body = JSON.parse(body);
          console.log(body);
        });

        res.on("error", e => {
            console.log("res.on('error')res.StatusCode:", e.message);
        });

    }); // End https.request()
}

https_get(); // This Works OK.

https_request(); // This doesn't work, it times-out with events.js:136 throw er; // Unhandled 'error' event ^ Error: socket hang up

...

https_get()
https_request()
-------------------------------
failed request options: { method: 'GET',
  host: 'api.postcodes.io',
  path: '/postcodes/SW1A1AA',
  headers: { 'Content-Type': 'application/json' } }
-------------------------------
{ status: 200,
  result: 
   { postcode: 'BL3 4HG',
     quality: 1,
     eastings: 369619,
     northings: 407887,

1 个答案:

答案 0 :(得分:1)

为您的请求添加错误处理程序,并致电req.end()

const req = https.request(options, res => {
    ...
})

req.on('error', (e) => {
    console.error(e);
});

req.end();

The Node docs explain why

  

请注意,在示例中调用了req.end()。用http.request()一个   必须始终调用req.end()来表示请求的结束 - 即使   没有数据写入请求正文。