2017-04-18 4 views
1

私は基本的に/ etc/hostsファイルのIPアドレスにマップされた内部URLを持っています。 URLにpingを実行すると、正しい内部IPアドレスが返されます。私はrequestノードモジュールに依存していたときに、問題が発生する:/etc/hostsの使用を強制的に要求する

の/ etc/hosts:

123.123.123.123 fakeurl.com 

app.js:

403エラー:

var request = require('request'); 
request('http://fakeurl.com/', function (error, response, body) { 
    console.log('error:', error); // Print the error if one occurred 
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
    console.log('body:', body); // Print the HTML for the page. 
}); 

は200のコードを動作します。

var request = require('request'); 
request('http://123.123.123.123/', function (error, response, body) { 
    console.log('error:', error); // Print the error if one occurred 
    console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received 
    console.log('body:', body); // Print the HTML for the page. 
}); 

ノードアプリケーション内でDNSマッピングを強制する方法はありますか?

+0

代わりにhttpモジュールを使用して試すことができますか? httpモジュールは/ etc/hostsに従って解決する必要があります。 – user3105700

+0

これは簡単だったと思います。実際に別のノードモジュールによって実行されているため、リクエストモジュールに縛られています。私はちょうどそれがなぜ起こって、それをバイパスする方法を見つけることを望んでいたの問題を絞りました。 – Woodsy

+0

私はこの同じ問題に直面しています。 Node.jsがhostsファイルを無視してリクエストを作成し続ける理由はわかりません。何か解決策を見つけましたか? – JamesYin

答えて

1

ノード()が使用するデフォルトのDNS解決方法は、システムリゾルバを使用します。システムリゾルバは、ほとんどの場合、/ etc/hostsを考慮に入れます。

ここでの違いは、DNS自体の解決には関係ありませんが、HTTP Hostフィールドの値と関係があります。最初のリクエストではHost: fakeurl.comが123.123.123.123のHTTPサーバーに送信され、2番目のリクエストではHost: 123.123.123.123が123.123.123.123のHTTPサーバーに送信されます。サーバは、これらの2つの要求を、その構成に応じて異なる方法で解釈することができる。

IPアドレスをHTTP Hostヘッダーフィールドの値として使用する場合は、手動でアドレスを解決する必要があります。例:

require('dns').lookup('fakeurl.com', (err, ip) => { 
    if (err) throw err; 
    request(`http://${ip}/`, (error, response, body) => { 
    // ... 
    }); 
}); 
関連する問題