Node.js getaddrinfo ENOTFOUND


265

Node.jsを使用して、次のWebページの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でWebサービスを呼び出す方法は?

node.jsでモジュールを使用していません。

読んでくれてありがとう。



使用していたvar http = require("http");か、var https = require("https");リモートホストに基づいて
— prayagupd

どういうENOTFOUND 意味ですか?
— チャーリーパーカー、

回答:


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フィールドに含めないでください。その他の回答でもhttps、SSLが必要な場合はモジュールの使用を推奨しています。


16
迅速な返信をありがとう、これは完璧に機能します!最初にドキュメントを読まないように自分の質問に反対票を投じるような気がします。
— Vineet Kosaraju 2013

2
私の問題は、nodejsスクリプト内で間違ったURLへのリクエストを作成していて、このエラーがスローされたことでした。
— マイケルJ.カルキンス

49
したがって、基本的には、次のように要約します。1.実際のホスト名のみをに含めるhostので、http://またはまたはhttps://; および2.パスをhostプロパティに含めず、プロパティに含めpathます。
— Eduard Luca、

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、...)を書き込んでいますhostoptions

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

7
これは、説明したエラーよりも一般的なエラーです。
— shaunakde、2015年

5
この代替ソリューションを投稿していただきありがとうございます。私はまさにこれに遭遇していました。
— ライアン

おかげで私はhttp.get()を使用するのと同じエラーをスローしたhttp.request()を使用していますが、http.request()でhttp://を削除して機能しました。
— Shashikant Pandit

17

HTTPリクエストのオプションで、次のように切り替えます。

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

それで問題は解決すると思います。


1
答えてくれてありがとう!これも完璧に機能しますが、ドキュメントへのリンクと2つのオプションがあるため、もう1つは正しいものとしてマークしました。
— Vineet Kosaraju 2013

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 2013

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でアプリケーションを実行するには、root権限が必要です。

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

この問題は、参照しているドメインがダウンした場合にも発生する可能性があることに注意してください(たとえば、存在しなくなりました)。


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 2013

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

私の問題は、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.