Error: getaddrinfo ENOTFOUND in nodejs for get call
Asked Answered
P

12

90

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?

Paryavi answered 24/4, 2014 at 4:16 Comment(2)
process.stdout.alwrite.now(d)Suburbanize
Does this answer your question? Node.js getaddrinfo ENOTFOUNDAl
G
134

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.

Greenquist answered 24/4, 2014 at 4:33 Comment(3)
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.Chenay
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.Stalker
If it doesn't work even if hosts files has the correct entry check /etc/nsswitch.conf has a line like hosts: mymachines files dns [!UNAVAIL=return] myhostname resolve networks: files. files should occur before [!UNAVAIL=return]. That is what worked for me.Pease
T
31

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
Tierney answered 10/1, 2017 at 19:11 Comment(1)
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!Karame
A
18

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

Apul answered 26/8, 2014 at 9:45 Comment(2)
What hostname did you add?Gertrude
@PerStröm 127.0.0.1 localhostConk
M
9

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.

Meatus answered 27/7, 2016 at 8:28 Comment(2)
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){......}Marchesa
Thank you! It worked for me too but I was setting up the S3 Adapter for PayloadCMS and MinIO locally (with docker run), for development.Hotspur
D
4

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
Dissect answered 6/10, 2021 at 13:22 Comment(0)
Y
2

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 -

Yance answered 12/10, 2015 at 4:17 Comment(0)
O
1

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

Ottoottoman answered 30/10, 2016 at 7:45 Comment(0)
T
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%)
Tagmeme answered 22/2, 2017 at 5:2 Comment(0)
I
0

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
Intuitional answered 28/9, 2019 at 14:57 Comment(0)
M
0

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.

Malfeasance answered 13/10, 2021 at 7:18 Comment(0)
L
0

I had getaddrinfo ENOTFOUND localhost:3000 error. Could not connect to my database. My issue was that I've created 2 different databases in one postgresql db server. All of my db server properties were set correctly. For example: host: localhost port: 5432 username: myUsername password: xxxxxx

Only when I checked "Connection String" in my db server properties it had different dbname. Not the one I were expected it to pick up on. Just double check properties "connection string" as well in your database server properties.

Lofton answered 18/1 at 8:30 Comment(0)
D
-3

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
Daugavpils answered 4/7, 2014 at 0:43 Comment(1)
You can't ping with http which is port 80. Ping uses ICMP with is port 1. You can ping localhost though.Joanne

© 2022 - 2024 — McMap. All rights reserved.