2017-04-18 35 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不断发出请求忽略主机文件。你有没有找到解决方案兄弟? – JamesYin

回答

1

节点(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) => { 
    // ... 
    }); 
});