我有一些看起来像这样的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
。是否有一个已知的原因可能会这样做?
答案 0 :(得分:1)
首先,让我们试试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)来做这种事情是一个很好的标准模块。
答案 1 :(得分:0)
看起来您可能正在确认我在创建http请求的新样式时遇到的错误。根据我的测试,我很确定它与在http header / options中设置内容类型有关。
我回到原来的方式(即http.createClient())并且有效。这就是我的建议