错误:getaddrinfo ENOTFOUND in nodejs for get call

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23259697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:12:40  来源:igfitidea点击:

Error: getaddrinfo ENOTFOUND in nodejs for get call

node.jsmongodbbackbone.jsexpressrestify

提问by nnm

I am running a web server on node the code for which is given below

我在节点上运行网络服务器,其代码如下

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

And then i want to do a get request in the following code

然后我想在下面的代码中做一个获取请求

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

I am just starting with node and i dont even know if this is the right way. I want to test the performance of express and restify.I have done a apache benchmark test for the server code i wrote and found contradicting results that restify is better.So i want to test out some more by making calls to remote services and then later read write to mongodb.The above code is my starting point.I am getting the error

我只是从节点开始,我什至不知道这是否是正确的方法。我想测试express和restify的性能。我对我写的服务器代码做了一个apache基准测试,发现restify更好的矛盾结果。所以我想通过调用远程服务来测试更多,然后再测试读写mongodb。上面的代码是我的起点。我收到错误

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

Am i atleast heading in the write direction? What is the right way to the kind of tests that i want to? Why did i get the result restify faster than express? Can anyone guide me to the best starting point tutorials for application in node/express/backbone and mongodb?

我至少在写方向吗?我想要的那种测试的正确方法是什么?为什么我得到的结果比快递更快?谁能指导我在 node/express/backbone 和 mongodb 中应用的最佳起点教程?

回答by Karol

getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without http:

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
};

Regarding learning resources, you won't go wrong if you start with http://www.nodebeginner.org/and then go through some good book to get more in-depth knowledge - I recommend Professional Node.js, but there's many out there.

关于学习资源,如果你从http://www.nodebeginner.org/开始,然后阅读一些好书来获得更深入的知识,你就不会出错- 我推荐Professional Node.js,但有很多那里。

回答by Ben Kim

for me it was because in /etc/hosts file the hostname is not added

对我来说这是因为在 /etc/hosts 文件中没有添加主机名

回答by neoerol

Check host file which like this

检查像这样的主机文件

##
# 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

回答by Jay Wick

I can't explain why, but changing url parameter from having localhostto 127.0.0.1on mongodb.MongoClient.connect()method on Windows 10 solved the issue.

我无法解释原因,但是在 Windows 10上将url 参数从必须更改localhost127.0.0.1onmongodb.MongoClient.connect()方法解决了这个问题。

回答by Naren Chejara

I also had same problem and I fixed it by using right proxy. Please double check your proxy settings if you are using proxy network.

我也有同样的问题,我使用正确的代理修复了它。如果您使用代理网络,请仔细检查您的代理设置。

Hope this will help you -

希望能帮到你 -

回答by Adiii

i have same issue with Amazon server i change my code to this

我对亚马逊服务器有同样的问题,我将代码更改为此

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

check mysql node module https://github.com/mysqljs/mysql

检查 mysql 节点模块 https://github.com/mysqljs/mysql

回答by Dr NVS

When I tried to install a new ionic app, I got the same error as follows, I tried many sources and found the mistake made in User Environment and System Environment unnecessarily included the PROXY value. I removed the ```user variables http://host:portPROXY

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

system Variables http_proxy http://username:password@host:port```` and now it is working fine without trouble.

系统变量 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

回答by Washington Guedes

Struggling for hours, couldn't afford for more.

挣扎了几个小时,负担不起更多。

The solution that worked for me in less than 3 minutes was:

在不到 3 分钟的时间内对我来说有效的解决方案是:

npm install axios

Code ended up even shorter:

代码最终变得更短:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface[]>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

回答by Er.Subhendu Kumar Pati

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%)

回答by Hady

I was running into the same problem and after some trial and error discovered that my hostsfile customisation was causing the problem.

我遇到了同样的问题,经过反复试验后发现是我的hosts文件自定义导致了问题。

My localhostDNS was overwritten and because of that a simple ping was failing:

我的localhostDNS 被覆盖,因此一个简单的 ping 失败:

$ ping http://localhost
# ping: cannot resolve http://localhost: Unknown host

Once I resolved the configuration of /private/etc/hostsfile, pinging localhostsuccessfully worked, and was no longer getting the error that you were seeing:

一旦我解决了/private/etc/hosts文件的配置,ping 就localhost成功了,并且不再出现您看到的错误:

# Fatal error: getaddrinfo ENOTFOUND