Node.js getaddrinfo ENOTFOUND


265

Node.js를 사용하여 다음 웹 페이지의 html 컨텐츠를 가져 오는 경우

eternagame.wikia.com/wiki/EteRNA_Dictionary

다음과 같은 오류가 발생합니다.

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)

나는 이미 stackoverflow 에서이 오류를 찾아 보았고 node.js가 DNS에서 서버를 찾을 수 없기 때문이라는 것을 깨달았습니다. 그러나 코드가 완벽하게 작동하기 때문에 왜 이것이 될지 잘 모르겠습니다 www.google.com.

내 코드는 다음과 같습니다 (호스트가 변경된 것을 제외하고는 매우 유사한 질문에서 실제로 복사하여 붙여 넣습니다).

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

: 여기에 복사하여 붙여 넣을 소스 인 방법 Expressjs에서 웹 서비스 호출을하는가?

node.js와 함께 모듈을 사용하지 않습니다.

읽어 주셔서 감사합니다.



원격 호스트 를 사용 var http = require("http");하거나 var https = require("https");기반으로 해야 함
prayagupd

무슨 ENOTFOUND 뜻입니까?
Charlie Parker

답변:


280

에서 Node.js를의 HTTP 모듈의 문서 : http://nodejs.org/api/http.html#http_http_request_options_callback

를 호출 http.get('http://eternagame.wikia.com/wiki/EteRNA_Dictionary', callback)하면 URL이 다음과 같이 구문 분석됩니다 url.parse(). 또는 호출 http.get(options, callback), 어디는 options것입니다

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

최신 정보

@EnchanterIO의 의견에서 언급했듯이이 port필드는 별도의 옵션이기도합니다. 프로토콜 http://host필드에 포함되어서는 안됩니다 . 다른 답변은 httpsSSL이 필요한 경우 모듈 사용을 권장 합니다.


16
빠른 답변 주셔서 감사합니다, 이것은 완벽하게 작동합니다! 나는 문서를 먼저 읽지 않은 것에 대한 내 자신의 질문을 무시하고 싶다.
Vineet Kosaraju

2
내 문제는 nodejs 스크립트 내에서 잘못된 URL을 요청 하고이 오류가 발생한다는 것입니다.
Michael J. Calkins

49
그러니까 기본적으로, 정리해 없습니다 : 1. 만의 실제 호스트 이름을 포함 host그래서, http://또는 https://; 그리고 2. host속성에 경로를 포함시키지 말고 속성에 경로를 포함하십시오 path.
에두아르드 루카

1
Learning Node의 샘플 코드는 이것을 명확하게하지 못했습니다. 이제 options {...}블록을 채울 때 왜 이상한 실패가 발생했는지 이해합니다 .
Michael Shopsin

+ 포트가 호스트와 별도의 옵션 속성인지 확인하십시오.
Lukas Lukac

240

에 대한 또 다른 일반적인 오류 원인

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

속성을 설정할 때 프로토콜 (https, https, ...)을 쓰고 host있습니다.options

  // DON'T WRITE THE `http://`
  var options = { 
    host: 'http://yoururl.com',
    path: '/path/to/resource'
  }; 

7
이것은 논의 된 것보다 더 일반적인 오류입니다.
shaunakde

5
이 대안 솔루션을 게시 해 주셔서 감사합니다.
Ryan

감사합니다 @ 조지 나는 http.request ()를 사용하고 있습니다.
Shashikant Pandit

17

HTTP 요청에 대한 옵션에서

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

나는 그것이 당신의 문제를 해결할 것이라고 생각합니다.


1
답변 해주셔서 감사합니다! 이것은 또한 완벽하게 작동하지만 다른 하나는 문서와 두 가지 옵션에 대한 링크가 있기 때문에 올바른 것으로 표시했습니다.
Vineet Kosaraju

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

  });

답변 해주셔서 감사합니다! Russbear의 답변과 마찬가지로이 기능은 완벽하게 작동하지만 옵션과 문서에 대한 링크를 모두 제공했기 때문에 yuxhuang의 올바른 것으로 표시했습니다.
Vineet Kosaraju

1
문제와 솔루션이 실제로 완전한 대답이 아닌 것을 설명하지 않고 코드를 작성하면 코드 블록에서 수행 한 작업을 볼 수 없습니다. 감사합니다.
Al-Mothafar

11

https를 사용해야하는 경우 https 라이브러리를 사용하십시오.

https = require('https');

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

// get
https.get(options, callback);


7

옵션 객체에서 완전한 호스트 URL을 언급했지만 http가 포트 80에서 요청한다고 생각합니다. 이전에 포트 3000에서 실행했던 포트 80에서 API가있는 서버 응용 프로그램을 실행할 때 작동했습니다. 포트 80에서 응용 프로그램을 실행하려면 루트 권한이 필요합니다.

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

다음은 완전한 코드 스 니펫입니다.

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

이 답변에서 중요한 부분은 프로토콜입니다. nodejs HTTP 전체 URI를 지원하지 host: https://server.com뿐만 아니라 여기에 언급, stackoverflow.com/a/28385129/432903
prayagupd

3

참조하는 도메인이 다운 된 경우에도이 문제가 발생할 수 있습니다 (EG. 더 이상 존재하지 않음).


3

이 오류를 해결했습니다.

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

원본 출처 : https://github.com/npm/npm/issues/6686



1

요청 모듈을 사용하여 시도해 보았고 해당 페이지의 본문을 아주 쉽게 인쇄 할 수있었습니다. 불행히도 내가 가진 기술로는 그 외에는 도울 수 없습니다.


모듈에 대한 링크에 감사하지만 http.get ()을 사용하여 표준 node.js 라이브러리 로이 작업을 수행하려고했습니다.
Vineet Kosaraju

0

개발 환경에서 프로덕션 환경으로 갈 때이 오류가 발생했습니다. 나는 https://모든 링크 를 씌우는 것에 집착했다 . 이것은 필요하지 않으므로 일부에게는 해결책이 될 수 있습니다.


0

http와 추가 슬래시 (/)를 제거했습니다. 방금이 'node-test.herokuapp.com'을 사용했으며 효과가있었습니다.


0

여전히 프록시 설정 체크 아웃에 직면 한 경우 프록시 설정이 누락되어 직접 http / https가 차단되어 요청을 할 수 없었습니다. 그래서 요청을하는 동안 조직에서 프록시를 구성했습니다.

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

연결 암호에서 원하지 않는 문자를 제거 하여이 문제를 해결했습니다. 예를 들어, <## % 문자가 문제를 일으켰습니다 (해시 태그가 문제의 근본 원인 일 수 있음).


0

호스트 이름 대신 서버 IP 주소를 사용해보십시오. 이것은 나를 위해 일했습니다. 그것이 당신에게도 효과가 있기를 바랍니다.


0

내 문제는 URL을 구문 분석하고 http.request ()에 대한 http_options를 생성하는 것이 었습니다.

도메인 이름을 가진 포트 번호가 이미있는 request_url.host를 사용하고 있었으므로 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;
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.