ChatGPT解决这个技术问题 Extra ChatGPT

Error: getaddrinfo ENOTFOUND in nodejs for get call

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

{ [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?

process.stdout.alwrite.now(d)
Does this answer your question? Node.js getaddrinfo ENOTFOUND

K
Karol

getaddrinfo ENOTFOUND means client was not able to connect to given address. Please try specifying host without 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.


getaddrinfo ENOUTFOUND means client was not able to connect... -> Make sure that you get a reply when you ping that address using a terminal or prompt.
If you have localhost as your host and it still doesn't work, check your \etc\hosts file if it has this row: 127.0.0.1 localhost.
M
Michael_Scharf

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

This solved the problem for me! After hours of search, I found that the /etc/hosts file on my mac was empty! After you change the file on the mac, run sudo killall -HUP mDNSResponder for the changed to take effect!
B
Ben Kim

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


What hostname did you add?
@PerStröm 127.0.0.1 localhost
J
Jay Wick

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


Something similar worked on OSX sierra, I tried connecting with MongoClient.connect('mongodb://localhost:27017/meanhotel', function(err, db){......} But this worked instead: MongoClient.connect('mongodb://127.0.0.1:27017/meanhotel', function(err, db){......}
N
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 -


A
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


T
T3rm1

My problem was that my endpoint was http://tenant1.localhost. While this somehow works in the browser, it did not with node.

I had to add the following line to /etc/hosts

127.0.0.1 tenant1.localhost

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

D
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:port PROXY

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

[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

P
Popescu M

I had a similar issue and it turned out the issue was with my proxy password.

The error was:

"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'

It turned out the interesting part was this one :

failed, reason: getaddrinfo ENOTFOUND myUsername

My password, that was used in the proxy, had special characters like ! and #. After I used percent encoding : https://en.wikipedia.org/wiki/Percent-encoding I was able to run npm install. Before this I tried with a wrong password and a received a 407 error.


H
Hady

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

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

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

Once I resolved the configuration of /private/etc/hosts file, pinging localhost successfully worked, and was no longer getting the error that you were seeing:

# Fatal error: getaddrinfo ENOTFOUND

You can't ping with http which is port 80. Ping uses ICMP with is port 1. You can ping localhost though.

关注公众号,不定期副业成功案例分享
Follow WeChat

Success story sharing

Want to stay one step ahead of the latest teleworks?

Subscribe Now