Node.js getaddrinfo ENOTFOUND
Asked Answered
B

19

404

When using Node.js to try and get the html content of the following web page:

eternagame.wikia.com/wiki/EteRNA_Dictionary

I get the following error:

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)

I did already look up this error on stackoverflow, and realized that this is because node.js cannot find the server from DNS (I think). However, I am not sure why this would be, as my code works perfectly on www.google.com.

Here is my code (practically copied and pasted from a very similar question, except with the host changed):

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

Here is the source where I copied and pasted from : How to make web service calls in Expressjs?

I am not using any modules with node.js.

Thanks for reading.

Batavia answered 17/7, 2013 at 3:54 Comment(3)
had to use var http = require("http"); or var https = require("https"); based on remote hostWharton
what does ENOTFOUND mean?Notability
@CharlieParker it is DNS error meaning address cannot be resolvedHeng
M
382

In Node.js HTTP module's documentation: http://nodejs.org/api/http.html#http_http_request_options_callback

You can either call http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', callback), the URL is then parsed with url.parse(); or call http.get(options, callback), where options is

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

Update

As stated in the comment by @EnchanterIO, the port field is also a separate option; and the protocol http:// shouldn't be included in the host field. Other answers also recommends the use of https module if SSL is required.

Mollusc answered 17/7, 2013 at 5:8 Comment(6)
My issue was that within my nodejs script I was making a request to the wrong url and this error was thrown.Hypochlorite
So basically, to sum it up: 1. Only include the actual hostname in host, so no http:// or https://; and 2. Don't include the path in the host property, but rather in the path property.Deakin
My sample code in Learning Node did not make this clear to me. Now I understand why I got strange failures when I filled out the options {...} block.Toland
+ make sure the port is also in a separate option attribute from host.Eugenieeugenio
As stated by @Jorge Bucaran in a separate Answer : IT IS UTTERLY IMPORTANT to not include http:// in the option.host definition (was the main reason of my error)Marindamarinduque
I had included https:// in the host, removing this helped to fix the issue. Thanks @MolluscSpelldown
A
285

Another common source of error for

Error: getaddrinfo ENOTFOUND
    at errnoException (dns.js:37:11)
    at Object.onanswer [as oncomplete] (dns.js:124:16)

is writing the protocol (https, https, ...) when setting the host property in options

  // DON'T WRITE THE `http://`
  var options = { 
    host: 'http://yoururl.com',
    path: '/path/to/resource'
  }; 
Aleciaaleck answered 7/2, 2015 at 17:26 Comment(4)
This is a more general error than the one discussed.Ideomotor
Thanks @Jorge i am using http.request() which thrown error the same i was going to use http.get() but i just removed http:// with http.request() and worked.Kalmar
+1 for this. In my case i want to get APP_URL env on vitejs bundler, but the error show up. So i remove the protocol http / https and it worksJosselyn
Good tip! Where then should the protocol be specified?Killen
A
29

My problem was that my OS X (Mavericks) DNS service needed to be restarted. On Catalina and Big Sur DNS cache can be cleared with:

sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

Older macOS versions see here.

Aliquot answered 13/7, 2015 at 21:55 Comment(0)
Y
22

in the options for the HTTP request, switch it to

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

I think that'll fix your problem.

Yeager answered 17/7, 2013 at 5:7 Comment(1)
Thanks for the answer! This also works perfectly, but I marked the other one as correct because it has a link to the docs and two options.Batavia
R
12

If you need to use https, then use the https library

https = require('https');

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

// get
https.get(options, callback);
Ritzy answered 10/8, 2016 at 23:39 Comment(0)
C
11
  var http=require('http');
   http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', function(res){
        var str = '';
        console.log('Response is '+res.statusCode);

        res.on('data', function (chunk) {
               str += chunk;
         });

        res.on('end', function () {
             console.log(str);
        });

  });
Cylindrical answered 17/7, 2013 at 6:23 Comment(2)
Thanks for the answer! Just like Russbear's answer, this one works perfectly but I marked yuxhuang's correct because he gave both options and a link to the docs.Batavia
Just code without explaining what the problem and what the solution is not really a complete answer, I don't see what you did in your block of code, thanks.Ardel
I
9

I think http makes request on port 80, even though I mentioned the complete host url in options object. When I run the server application which has the API, on port 80, which I was running previously on port 3000, it worked. Note that to run an application on port 80 you will need root privilege.

Error with the request: getaddrinfo EAI_AGAIN localhost:3000:80

Here is a complete code snippet

var http=require('http');

var options = {
  protocol:'http:',  
  host: 'localhost',
  port:3000,
  path: '/iso/country/Japan',
  method:'GET'
};

var callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
}

var request=http.request(options, callback);

request.on('error', function(err) {
        // handle errors with the request itself
        console.error('Error with the request:', err.message);        
});

request.end();
Intercross answered 30/5, 2017 at 7:13 Comment(1)
the important part in this answer is protocol. nodejs http did not support full uri with host: https://server.com, which is mentioned here as well https://mcmap.net/q/86401/-node-js-getaddrinfo-enotfoundWharton
T
6

I fixed this error with this

$ npm info express --verbose
# Error message: npm info retry will retry, error on last attempt: Error: getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
$ nslookup registry.npmjs.org
Server:     8.8.8.8
Address:    8.8.8.8#53

Non-authoritative answer:
registry.npmjs.org  canonical name = a.sni.fastly.net.
a.sni.fastly.net    canonical name = prod.a.sni.global.fastlylb.net.
Name:   prod.a.sni.global.fastlylb.net
Address: 151.101.32.162
$ sudo vim /etc/hosts 
# Add "151.101.32.162 registry.npmjs.org` to hosts file
$ npm info express --verbose
# Works now!

Original source: https://github.com/npm/npm/issues/6686

Tiro answered 5/1, 2018 at 9:49 Comment(0)
E
5

In my case the problem was a malformed URL. I had double slashes in the URL.

Ezara answered 27/4, 2022 at 1:42 Comment(0)
T
4

Note that this issue can also occur if the domain you are referencing goes down (EG. no longer exists.)

Treadwell answered 11/8, 2015 at 18:11 Comment(0)
K
3

in my case error was because of using incorrect host value was

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

should be

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

so anything after .com or .net etc should be moved to path parameter value

Kus answered 27/12, 2020 at 16:27 Comment(1)
Me too! Removed https:// and it worked great. Many thanks.Montpelier
G
1

I tried it using the request module, and was able to print the body of that page out pretty easily. Unfortunately with the skills I have, I can't help other than that.

Glen answered 17/7, 2013 at 5:7 Comment(1)
Thanks for the link to the module, but I was hoping to do this with the standard node.js library, using http.get().Batavia
T
1

I got this error when going from development environment to production environment. I was obsessed with putting https:// on all links. This is not necessary, so it may be a solution for some.

Triumvirate answered 12/6, 2015 at 10:21 Comment(0)
C
1

I was getting the same error and used below below link to get help:

https://nodejs.org/api/http.html#http_http_request_options_callback

I was not having in my code:

req.end();

(NodeJs V: 5.4.0) once added above req.end(); line, I was able to get rid of the error and worked fine for me.

Cato answered 10/1, 2016 at 5:45 Comment(0)
H
1

Try using the server IP address rather than the hostname. This worked for me. Hope it will work for you too.

Homebred answered 6/1, 2019 at 8:22 Comment(0)
T
1

My problem was we were parsing url and generating http_options for http.request();

I was using request_url.host which already had port number with domain name so had to use 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;
Triage answered 8/8, 2019 at 7:4 Comment(1)
this one did the trick, thanks :)Collection
G
0

I got rid of http and extra slash(/). I just used this 'node-test.herokuapp.com' and it worked.

Gladiate answered 22/7, 2016 at 10:29 Comment(0)
I
0

If still you are facing checkout for proxy setting, for me it was the proxy setting which were missing and was not able to make the request as direct http/https are blocked. So i configured the proxy from my organization while making the request.

npm install https-proxy-agent 
or 
npm install http-proxy-agent

const httpsProxyAgent = require('https-proxy-agent');
const agent = new httpsProxyAgent("http://yourorganzation.proxy.url:8080");
const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  agent: agent
};
Immigrate answered 9/6, 2017 at 9:19 Comment(0)
K
0

I got this issue resolved by removing non-desirable characters from the password for the connection. For example, I had these characters: <##% and it caused the problem (most probably hash tag was the root cause of the problem).

Karachi answered 1/9, 2017 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.