请求.org域名时,节点http模块错误

当我使用http模块来获得一个.org域名时,我得到了一个400响应。 (尝试google.org所以这不是一个服务器错误。)这是正常的行为?

var http = require('http'); http.get("google.org", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); }); 

您的代码发出以下HTTP请求:

 GET google.org HTTP/1.1 Host: localhost 

这是你的本地机器正在响应400(因为请求确实无效)。 发生这种情况是因为内部节点使用url模块parsing传递给http.get的string。 url将stringgoogle.org视为相对path。

 url.parse('google.org'); { protocol: null, slashes: null, auth: null, host: null, port: null, hostname: null, hash: null, search: null, query: null, pathname: 'google.org', path: 'google.org', href: 'google.org' } 

由于您的stringparsing为空主机名,节点默认使用本地主机。

尝试使用完全合格的url。

 var http = require('http'); http.get("http://google.org", function(res) { console.log("Got response: " + res.statusCode); }).on('error', function(e) { console.log("Got error: " + e.message); });