Nodo.js getaddrinfo ENOTFOUND


Cuando se usa Node.js para intentar obtener el contenido html de la siguiente página web:

eternagame.wikia.com/wiki/EteRNA_Dictionary

Obtengo el siguiente 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)

Ya busqué este error en stackoverflow, y me di cuenta de que esto es porque node.js no puede encontrar el servidor desde DNS (creo). Sin embargo, no estoy seguro de por qué sería esto, ya que mi código funciona perfectamente en www.google.com.

Aquí está mi código (prácticamente copiado y pegado de una pregunta muy similar, excepto con el host cambiado):

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

Aquí está la fuente desde la que copié y pegué : ¿Cómo hacer llamadas a servicios web en Expressjs?

No estoy usando ningún módulo con node.js.

Gracias por leer,

Vineet

 176
Author: Community, 2013-07-17

16 answers

En El Nodo .js HTTP documentación del módulo: http://nodejs.org/api/http.html#http_http_request_options_callback

Puede llamar a http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', callback), la URL se analiza con url.parse(); o llamar http.get(options, callback), donde options es

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

Update

Como se indica en el comentario de @EnchanterIO, el campo port también es una opción separada; y el protocolo http:// no debe incluirse en el campo host. Otras respuestas también recomienda el uso de https módulo si se requiere SSL.

 188
Author: yuxhuang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-14 19:33:23

Otra fuente común de error para

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

Está escribiendo el protocolo (https, https,...) al establecer la propiedad host en options

  // DON'T WRITE THE `http://`
  var options = { 
    host: 'http://yoururl.com',
    path: '/path/to/resource'
  }; 
 202
Author: Jorge Bucaran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-27 19:49:40

En las opciones para la solicitud HTTP, cámbiela a

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

Creo que eso solucionará tu problema.

 16
Author: Russbear,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 05:07:52
  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);
        });

  });
 11
Author: sachin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-25 10:21:15

Si necesita usar https, use la biblioteca https

https = require('https');

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

// get
https.get(options, callback);
 8
Author: Andrew,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-10 23:39:12

Mi problema era que mi servicio DNS de OS X (Mavericks) necesitaba ser reiniciado.

 6
Author: aaaidan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-13 21:55:44

Tenga en cuenta que este problema también puede ocurrir si el dominio al que hace referencia se cae (por EJEMPLO. ya no existe.)

 3
Author: Mauvis Ledford,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-08-11 18:11:21

Creo que http hace una solicitud en el puerto 80, a pesar de que mencioné la url completa del host en el objeto options. Cuando ejecuté la aplicación de servidor que tiene la API, en el puerto 80, que estaba ejecutando anteriormente en el puerto 3000, funcionó. Tenga en cuenta que para ejecutar una aplicación en el puerto 80 necesitará privilegios de root.

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

Aquí hay un fragmento de código completo

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();
 3
Author: Mahtab Alam,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 07:13:17

Estaba recibiendo el mismo error y se utiliza a continuación el siguiente enlace para obtener ayuda:

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

No estaba teniendo en mi código:

req.end();

(NodeJS V: 5.4.0) una vez agregado encima de la línea req.end();, pude deshacerme del error y funcionó bien para mí.

 2
Author: sudeep patel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-01 20:10:27

Arreglé este error con este

$ 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!

Fuente original: https://github.com/npm/npm/issues/6686

 2
Author: Mertcan Diken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-14 19:36:28

Lo probé usando el módulo de solicitud , y pude imprimir el cuerpo de esa página con bastante facilidad. Desafortunadamente con las habilidades que tengo, no puedo ayudar más que eso.

 1
Author: AberZombie,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-17 06:55:03

Obtuve este error al pasar del entorno de desarrollo al entorno de producción. Estaba obsesionado con poner https:// en todos los enlaces. Esto no es necesario, por lo que puede ser una solución para algunos.

 0
Author: petur,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-12 10:21:46

Me deshice de http y extra slash(/). Acabo de usar esto .node-test.herokuapp.com y funcionó.

 0
Author: Uday Reddy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-22 10:29:09

Si todavía se enfrenta a la comprobación para la configuración de proxy, para mí fue la configuración de proxy que faltaban y no fue capaz de hacer la solicitud ya que http/https directos están bloqueados. Así que configuré el proxy de mi organización mientras realizaba la solicitud.

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
};
 0
Author: Ansar Ahmed,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-09 09:19:58

Resolví este problema eliminando los caracteres no deseables de la contraseña para la conexión. Por ejemplo, tenía estos caracteres:

 0
Author: Shota,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-01 06:49:56

La solución a este error para mí fue instalar http con node package manager:

npm install http-server -g
 -5
Author: Jamie M.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-25 14:58:15