我有一些如下所示的 node.js 代码:
Updater.prototype.poll= function(callback) {
var options = {
host: api_host,
port: 80,
path: update_path,
method: 'GET',
agent: false,
headers: [{'accept-encoding': '*;q=1,gzip=0'}]
};
console.log('Polling');
var req = http.get(options, function(res) {
//other stuff here...
});
};
问题是发送请求时,服务器返回400 Bad Request - Invalid Hostname
。我用 wireshark 嗅探了 TCP 流,它似乎没有发送 http 请求的 Host
部分,而是生成了一行看起来像:undefined: undefined
.我确定 api_host
变量设置正确(我什至尝试过使用硬编码字符串)。我也尝试过使用 hostname
而不是 host
。它可能以这种方式行事是否有已知原因?
最佳答案
首先,让我们试试node.js docs中的示例页。这对你有用吗?如果在这里更换主机怎么办?
var options = {
host: 'www.google.com',
port: 80,
path: '/index.html'
};
http.get(options, function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});
其次,您是否考虑过使用 Request ?它是用更友好的语法(类似于 jQuery)做这类事情的标准模块。
关于http - node.js http.get() 发出请求而不发送主机名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9956788/