I basically have an internal url that is mapped to an ip address in the /etc/hosts file. When I do a ping on the url the correct internal ip address is returned. Problems arise when I rely on the request node module:
/etc/hosts:
123.123.123.123 fakeurl.com
app.js:
403 error:
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.
});
works 200 code:
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.
});
Is there a way to force the dns mapping within the node app?
The default DNS resolution method used by node (dns.lookup()) uses the system resolver, which almost always takes /etc/hosts into account.
The difference here has nothing to do with DNS resolution per se, but most likely instead has to do with the value used for the HTTP Host field. In the first request Host: fakeurl.com will be sent to the HTTP server at 123.123.123.123, whereas in the second request Host: 123.123.123.123 will be sent to the HTTP server at 123.123.123.123. The server may interpret these two requests differently depending on their configuration.
So you will need to manually resolve the address if you want to use the IP address as the HTTP Host header field value. For example:
require('dns').lookup('fakeurl.com', (err, ip) => {
if (err) throw err;
request(`http://${ip}/`, (error, response, body) => {
// ...
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With