错误:在 Node.js 中进行 get 调用时出现 getaddrinfo ENOTFOUND

86

我正在运行一个基于Node的Web服务器,以下是其代码:

var restify = require('restify');

var server = restify.createServer();

var quotes = [
  { author : 'Audrey Hepburn', text : "Nothing is impossible, the word itself says 'I'm possible'!"},
  { author : 'Walt Disney', text : "You may not realize it when it happens, but a kick in the teeth may be the best thing in the world for you"},
  { author : 'Unknown', text : "Even the greatest was once a beginner. Don't be afraid to take that first step."},
  { author : 'Neale Donald Walsch', text : "You are afraid to die, and you're afraid to live. What a way to exist."}
];

server.get('/', function(req, res) {
  res.json(quotes);
});

server.get('/quote/random', function(req, res) {
  var id = Math.floor(Math.random() * quotes.length);
  var q = quotes[id];
  res.json(q);
});

server.get('/quote/:id', function(req, res) {
  if(quotes.length <= req.params.id || req.params.id < 0) {
    res.statusCode = 404;
    return res.send('Error 404: No quote found');
  }

  var q = quotes[req.params.id];
  res.json(q);
});

server.listen(process.env.PORT || 3011);

然后我想在以下代码中进行一个GET请求

var https = require('http');

/**
 * HOW TO Make an HTTP Call - GET
 */
// options for GET
var optionsget = {
    host : 'http://localhost',
    port : 3010,
    path : '/quote/random', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

console.info('Options prepared:');
console.info(optionsget);
console.info('Do the GET call');

// do the GET request
var reqGet = https.request(optionsget, function(res) {
    console.log("statusCode: ", res.statusCode);
    // uncomment it for header details
//  console.log("headers: ", res.headers);


    res.on('data', function(d) {
        console.info('GET result:\n');
        process.stdout.write(d);
        console.info('\n\nCall completed');
    });

});

reqGet.end();
reqGet.on('error', function(e) {
    console.error(e);
});

我刚开始学习Node.js,甚至不知道这是正确的方法。 我想测试Express和Restify的性能。我对我编写的服务器代码进行了Apache基准测试,并发现Restify表现更好。因此,我想通过调用远程服务进行更多测试,然后再读写MongoDB。以上代码是我的起点,但是出现了错误。

{ [Error: getaddrinfo ENOTFOUND] code: 'ENOTFOUND', errno: 'ENOTFOUND', syscall: 'getaddrinfo' }

我是否至少朝着正确的方向前进了?我想要进行的测试方式是什么?为什么restify比express更快?有人能指导我在node/express/backbone和mongodb应用方面的最佳起点教程吗?


process.stdout.alwrite.now(d) - nerdfiles
这个回答解决了你的问题吗?Node.js getaddrinfo ENOTFOUND - Henke
11个回答

129

getaddrinfo ENOTFOUND 表示客户端无法连接到给定的地址。请尝试在主机名中不包含 http:

var optionsget = {
    host : 'localhost',
    port : 3010,
    path : '/quote/random', // the rest of the url with parameters if needed
    method : 'GET' // do GET
};

关于学习资源,如果你从http://www.nodebeginner.org/开始并阅读一些好的书籍以获得更深入的知识,就不会走错路 - 我推荐Professional Node.js ,但市面上有很多其他书籍可供选择。


getaddrinfo ENOUTFOUND 意味着客户端无法连接...请确保在终端或提示符中使用 ping 命令能够收到该地址的回复。 - Michael Plautz
9
如果您的主机名称为 localhost 但仍无法正常工作,请检查您的 \etc\hosts 文件是否包含以下行:127.0.0.1 localhost。请注意,本地化名称“localhost”不能被更改。 - totymedli

28

检查类似以下的主机文件

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost

3
这解决了我的问题!经过几个小时的搜索,我发现我的 Mac 上的 /etc/hosts 文件是空的!在你更改 Mac 上的文件后,运行 sudo killall -HUP mDNSResponder 以使更改生效! - Michael_Scharf

18

对我而言,是因为在/etc/hosts文件中没有添加主机名


你添加了什么主机名? - Joe
1
@PerStröm 127.0.0.1 localhost - vimal1083

8
我不知道原因,但是在Windows 10上将url参数从localhost改为127.0.0.1,可以解决使用mongodb.MongoClient.connect()方法时出现的问题。

1
类似的方法在OSX Sierra上可行,我尝试连接MongoClient.connect('mongodb://localhost:27017/meanhotel', function(err, db){......},但是这个方法没有成功。相反,使用以下方法成功了:MongoClient.connect('mongodb://127.0.0.1:27017/meanhotel', function(err, db){......} - user1528506

3
我的问题是我的端点是http://tenant1.localhost。虽然这在浏览器中可以工作,但在 node 中却不能。
我不得不将以下行添加到 /etc/hosts 文件中。
127.0.0.1 tenant1.localhost

2

我曾经也遇到了同样的问题,但是我通过使用正确的代理解决了它。 如果你正在使用代理网络,请仔细检查你的代理设置。

希望这能帮到你 -


1

我和Amazon服务器遇到了同样的问题,我把我的代码改成了这个

var connection = mysql.createConnection({
    localAddress     : '35.160.300.66',
    user     : 'root',
    password : 'root',
    database : 'rootdb',
});

检查 MySQL Node 模块 https://github.com/mysqljs/mysql


0

我曾经遇到过类似的问题,后来发现是代理密码的问题。

错误信息如下:

"Start npm npm ERR! code ENOTFOUND npm ERR! errno ENOTFOUND npm ERR! network request to https://registry.npmjs.org/tslib/-/tslib-1.14.1.tgz failed, reason: getaddrinfo ENOTFOUND myUsername npm ERR! network This is a problem related to network connectivity. npm ERR! network In most cases you are behind a proxy or have bad network settings. npm ERR! network npm ERR! network If you are behind a proxy, please make sure that the npm ERR! network 'proxy' config is set properly. See: 'npm help config'

有趣的部分在这里:

failed, reason: getaddrinfo ENOTFOUND myUsername

我的密码中包含像!和#这样的特殊字符,用于代理。 在我使用百分号编码之后: https://en.wikipedia.org/wiki/Percent-encoding 我能够运行npm安装程序。 在此之前,我尝试使用错误的密码,收到了407错误。


0
var http = require('http');

  var options = {     
      host: 'localhost',
      port: 80,
      path: '/broadcast'
    };

  var requestLoop = setInterval(function(){

      http.get (options, function (resp) {
        resp.on('data', function (d) {
          console.log ('data!', d.toString());
        });
        resp.on('end', function (d) {
           console.log ('Finished !');
        });
      }).on('error', function (e) {
          console.log ('error:', e);
      });
  }, 10000);

var dns = require('dns'), cache = {};
dns._lookup = dns.lookup;
dns.lookup = function(domain, family, done) {
    if (!done) {
        done = family;
        family = null;
    }

    var key = domain+family;
    if (key in cache) {
        var ip = cache[key],
            ipv = ip.indexOf('.') !== -1 ? 4 : 6;

        return process.nextTick(function() {
            done(null, ip, ipv);
        });
    }

    dns._lookup(domain, family, function(err, ip, ipv) {
        if (err) return done(err);
        cache[key] = ip;
        done(null, ip, ipv);
    });
};

// Works fine (100%)

0
当我尝试安装一个新的ionic应用时,我遇到了如下相同的错误, 我尝试了很多来源,并发现在用户环境和系统环境中不必要地包含了PROXY值的错误。 我删除了```用户变量 http://host:port PROXY

系统变量 http_proxy http://username:password@host:port ```` 现在它可以正常工作,没有问题。

[ERROR] Network connectivity error occurred, are you offline?

        If you are behind a firewall and need to configure proxy settings, see: https://ion.link/cli-proxy-docs

        Error: getaddrinfo ENOTFOUND host host:80

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接