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

Get response of url in nodejs (express/http)

本文关键字:获取 url 响应 http nodejs express      更新时间:2023-09-26

我正在尝试在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();

我收到此错误

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)

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

https://www.google.com/pretend/this/exists.xml

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

http://www.google.com/pretend/this/exists.xml

给出有效的响应

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

有什么想法吗?

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

编辑 2 :

所以我试了这个

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

显然不支持HTTPS。

Error: Protocol:https: not supported.

您需要在请求中侦听error事件。如果没有附加处理程序,它将引发错误,但如果附加了一个处理程序,它将在异步回调中将错误作为参数传递。此外,如果您打算发出安全请求,则应将 https 模块用于 node,而不是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();

首先,您应该需要http或https模块,具体取决于您想要使用的内容:

var https = require('https');
var http = require('http');

http/https 模块是 Node.js 的核心之一,所以你不需要安装 npm install。

缺少的是侦听错误:

var url = 'https://www.google.com/pretend/this/exists.xml';
var options = {
   host: url.split('.com/')[0] + '.com',
   path: '/' + url.split('.com/')[1]
}; 
var req = https.request(options, function (res) {
  var str = ""; 
  res.on('data', function (chunk) {
    str += chunk;
  });
  res.on('end', function () {
    console.log(str);
  });
}); 
req.on('error', function (err) {
     console.log('Error message: ' + err);
});     
req.end();

我还将您的代码更新为更好的版本并澄清版本。

我更喜欢将请求 npm 模块用于 http 请求。您会收到一个标准回调。

var request = require('request');
opts = {
    url : 'https://www.google.com/pretend/this/exists.xml'
};
request.get(opts, function (error, response, body) {
    //Handle error, and body
});
request.post, request.put, request.head etc.

这允许对错误进行相当标准的处理。