Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force request to use /etc/hosts

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?

like image 491
Woodsy Avatar asked May 09 '26 08:05

Woodsy


1 Answers

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) => {
    // ...
  });
});
like image 139
mscdex Avatar answered May 12 '26 04:05

mscdex