简体   繁体   English

在Node.js中获得URL的响应(express / http)

[英]Get response of url in nodejs (express/http)

I'm trying to get the response of two URLs in nodejs but there's a problem with http.request. 我正在尝试在nodejs中获得两个URL的响应,但是http.request存在问题。 Here's what I have so far: 这是我到目前为止的内容:

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();

and I'm getting this error 我得到这个错误

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)

so I googled and got this stackoverflow issue nodejs httprequest with data - getting error getaddrinfo ENOENT in which the accepted answer says that you need to leave out the protocol.. but here's the issue, I need to check if 所以我用谷歌搜索并得到了这个有数据的 stackoverflow问题nodejs httprequest-得到错误的getaddrinfo ENOENT ,其中接受的答案说你需要省略协议..但这是问题,我需要检查是否

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

gives a 200 and if it doesn't (404) then I need to check if 给出200,如果没有(404),那么我需要检查

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

gives a valid response 给出有效的回应

So that's the issue, I need to check a response by specific protocol. 这就是问题,我需要通过特定协议检查响应。

Any ideas? 有任何想法吗?

edit: Just now looking at the http doc (lazy I know) and I'm seeing http.get example.. I'll try that now 编辑:刚才看http doc(懒惰,我知道),我看到的是http.get示例。

edit 2 : 编辑2:

so I tried this 所以我尝试了这个

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

and apparently https is not supported. 并且显然不支持https。

Error: Protocol:https: not supported.

You need to listen to the error event on the request. 您需要侦听请求中的error事件。 If there is no handler attached, it will throw the error, but if there is one attached, it will pass the error as an argument in the asynchronous callback. 如果没有附加处理程序,它将引发错误,但是如果有附加处理程序,它将在异步回调中将错误作为参数传递。 In addition, you should use the https module for node, not http if you intend to make a secure request. 此外,你应该使用https模块节点,而不是http ,如果你打算做一个安全的要求。 So try this: 所以试试这个:

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();

First you should require the http or https module, depending what you want use: 首先,您需要使用http或https模块,具体取决于您要使用的模块:

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

http/https modules is one of the cores of Node.js, so you don't need install with npm install. http / https模块是Node.js的核心之一,因此您不需要通过npm install进行安装。

And what is missing is listen to errors: 而缺少的是听错误:

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();

I also update your code to a better version and clarify version. 我还将您的代码更新为更好的版本并阐明版本。

I prefer to use the request npm module for http requests. 我更喜欢将请求npm模块用于http请求。 You get a standard callback. 您会收到一个标准的回调。

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.

This allows for a fairly standard handling of errors. 这允许对错误进行相当标准的处理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM