【发布时间】:2018-03-15 13:33:13
【问题描述】:
在下面的示例中,我尝试调用测试 REST api: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,
...
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)
【问题讨论】:
标签: node.js httprequest