当使用Node.js尝试获取以下网页的html内容时:

eternagame.wikia.com/wiki/EteRNA_Dictionary

我得到以下错误:

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)

我已经在stackoverflow上查找了这个错误,并意识到这是因为node.js无法从DNS中找到服务器(我认为)。然而,我不确定为什么会这样,因为我的代码在www.google.com上工作得很好。

下面是我的代码(实际上是从一个非常相似的问题复制和粘贴,除了主机更改):

var http = require("http");

var options = {
    host: 'eternagame.wikia.com/wiki/EteRNA_Dictionary'
};

http.get(options, function (http_res) {
    // initialize the container for our data
    var data = "";

    // this event fires many times, each time collecting another piece of the response
    http_res.on("data", function (chunk) {
        // append this chunk to our growing `data` var
        data += chunk;
    });

    // this event fires *one* time, after all the `data` events/chunks have been gathered
    http_res.on("end", function () {
        // you can use res.send instead of console.log to output via express
        console.log(data);
    });
});

这是我复制和粘贴的源代码:如何在Expressjs中进行web服务调用?

我没有使用node.js的任何模块。

感谢阅读。


当前回答

我的问题是我的OS X (Mavericks) DNS服务需要重新启动。在卡特琳娜和大苏尔DNS缓存可以清除:

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

旧的macOS版本见这里。

其他回答

在Node.js HTTP模块的文档中:http://nodejs.org/api/http.html#http_http_request_options_callback

你可以调用http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary',回调),然后URL会被URL .parse()解析;或者调用http。Get (options, callback),其中options是

{
  host: 'eternagame.wikia.com',
  port: 8080,
  path: '/wiki/EteRNA_Dictionary'
}

更新

正如在@EnchanterIO的评论中所述,端口字段也是一个单独的选项;协议http://不应该包含在host字段中。其他答案也建议使用https模块,如果需要SSL。

我的问题是我的OS X (Mavericks) DNS服务需要重新启动。在卡特琳娜和大苏尔DNS缓存可以清除:

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

旧的macOS版本见这里。

尝试使用服务器IP地址而不是主机名。 这对我很管用。希望这对你也有用。

我的问题是,我们正在解析url和生成http_options http.request();

我用的是request_url。主机已经有端口号和域名,所以必须使用request_url.hostname。

var request_url = new URL('http://example.org:4444/path');
var http_options = {};

http_options['hostname'] = request_url.hostname;//We were using request_url.host which includes port number
http_options['port'] = request_url.port;
http_options['path'] = request_url.pathname;
http_options['method'] = 'POST';
http_options['timeout'] = 3000;
http_options['rejectUnauthorized'] = false;

在我的例子中,错误是因为使用了不正确的主机值 是

  var options = {
    host: 'graph.facebook.com/v2.12/',
    path: path
  }

应该是

  var options = {
    host: 'graph.facebook.com',
    path: path
  }

因此。com或。net等之后的任何内容都应该移动到path parameter value