Node.js https.get()与事件一起使用https.request()超时。js:136 thrower;//未处理';错误';事件

Node.js https.get()与事件一起使用https.request()超时。js:136 thrower;//未处理';错误';事件,node.js,httprequest,Node.js,Httprequest,在下面的示例中,我试图调用测试RESTAPI:api.postcodes.io。使用https.get()的函数工作正常,使用https.request()的函数挂起然后超时。这有点奇怪 有人知道会发生什么吗?我尝试过无数种使用https.request()的方法,它们的行为方式都是一样的。示例代码: "use strict"; // // This is a working example of https.get() // const https = require("https")

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

有人知道会发生什么吗?我尝试过无数种使用https.request()的方法,它们的行为方式都是一样的。示例代码:

    "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,


向请求中添加错误处理程序,并调用
req.end()

:

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


非常感谢。看起来很明显,你已经指出了问题。哦,我的天啊,我不认为这是显而易见的!!!内部(在编写本文时)有几个示例将
req.end()
排除在示例之外,警告文本仅出现在http.request页面上(而不是https.request)。是因为
https.get()
在没有显式调用end的情况下工作,我发送的是同一个options对象!
        ccg: 'E38000016',
        nuts: 'UKD36' } } }

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

Error: socket hang up
    at createHangUpError (_http_client.js:330:15)
    at TLSSocket.socketOnEnd (_http_client.js:423:23)
    at TLSSocket.emit (events.js:164:20)
    at endReadableNT (_stream_readable.js:1054:12)
    at _combinedTickCallback (internal/process/next_tick.js:138:11)
    at process._tickCallback (internal/process/next_tick.js:180:9)
const req = https.request(options, res => {
    ...
})

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

req.end();