Node.js 请求.org域时出现节点http模块错误

Node.js 请求.org域时出现节点http模块错误,node.js,Node.js,当我使用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.

当我使用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(因为请求确实无效)。发生这种情况的原因是,节点使用解析传递给http.get的字符串。url将字符串google.org视为相对路径

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' }
由于字符串解析为空主机名,因此使用localhost将节点转换为空主机名

尝试使用完全限定的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);
});

你的代码看起来像什么?添加了我的代码。这只是docsOk中的一个例子,适用于google,但不适用于此站点:
var http=require('http');http.get(“http://isitup.org/,函数(res){console.log(“得到响应:+res.statusCode);})。在('error',函数(e){console.log(“得到错误:+e.message);})http模块的工作方式是否与常规浏览器的GET请求不同?完全不同的问题。您会注意到该站点的错误是403(禁止)。该网站说“任何客户端(浏览器或bot)在使用isitup及其api时都必须提供准确和适当的用户代理描述。”除非您指定UA,否则Node不会发送UA。