强制请求使用/ etc / hosts

时间:2017-04-18 17:49:54

标签: node.js proxy request hosts

我基本上有一个内部URL,它被映射到/ etc / hosts文件中的ip地址。当我对url执行ping操作时,会返回正确的内部ip地址。当我依赖request节点模块时会出现问题:

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

有没有办法在节点app中强制执行dns映射?

1 个答案:

答案 0 :(得分:2)

节点(dns.lookup())使用的默认DNS解析方法使用系统解析器,它几乎总是将/ etc / hosts考虑在内。

这里的差异与DNS解析本身无关,但很可能与HTTP Host字段使用的值有关。在第一个请求中,Host: fakeurl.com将被发送到HTTP服务器123.123.123.123,而在第二个请求Host: 123.123.123.123将被发送到HTTP服务器123.123.123.123。服务器可能会根据其配置对这两个请求进行不同的解释。

因此,如果要将IP地址用作HTTP Host标头字段值,则需要手动解析地址。例如:

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