在 nodejs (express/http) 中获取 url 的响应

use*_*041 3 javascript http node.js express

我试图在 nodejs 中获取两个 URL 的响应,但是 http.request 存在问题。这是我到目前为止所拥有的:

var url = "https://www.google.com/pretend/this/exists.xml";

var opt = {
    host: url.split(".com/")[0] + ".com",
    path: "/" + url.split(".com/")[1]
};
callback = function(response){
    var str = "";
    response.on('data', function(chunk){
        str += chunk;
    });
    response.on('end', function(){
        console.log(str);
    });
}
http.request(opt, callback).end();
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

events.js:72
    throw er; // Unhandled 'error' event
          ^
Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)
Run Code Online (Sandbox Code Playgroud)

所以我用谷歌搜索并得到了这个stackoverflow问题 nodejs httprequest with data - 得到错误getaddrinfo ENOENT,其中接受的答案说你需要忽略协议..但这是问题所在,我需要检查是否

https://www.google.com/pretend/this/exists.xml
Run Code Online (Sandbox Code Playgroud)

给出 200,如果没有(404),那么我需要检查是否

http://www.google.com/pretend/this/exists.xml
Run Code Online (Sandbox Code Playgroud)

给出有效的回应

所以这就是问题所在,我需要检查特定协议的响应。

有任何想法吗?

编辑:刚才在看 http 文档(我知道是懒惰的),我看到了 http.get 示例..我现在就试试

编辑2:

所以我试过这个

http.get(url, function(res){
    console.log("response: " + res.statusCode);
}).on('error', function(e){
    console.log("error: " + e.message);
});
Run Code Online (Sandbox Code Playgroud)

显然不支持https。

Error: Protocol:https: not supported.
Run Code Online (Sandbox Code Playgroud)

Pat*_*rts 5

您需要监听error请求上的事件。如果没有附加处理程序,它将抛出错误,但如果附加了一个处理程序,它将在异步回调中将错误作为参数传递。此外,您应该使用httpsnode 模块,而不是http如果您打算发出安全请求。所以试试这个:

var https = require("https");

var url = "https://www.google.com/pretend/this/exists.xml";

var opt = {
    host: url.split(".com/")[0] + ".com",
    path: "/" + url.split(".com/")[1]
};

function callback(response) {
    var str = "";

    response.on("data", function (chunk) {
        str += chunk;
    });

    response.on("end", function () {
        console.log(str);
    });
}

var request = https.request(opt, callback);

request.on("error", function (error) {
    console.error(error);
});

request.end();
Run Code Online (Sandbox Code Playgroud)