【问题标题】:node.js http.get() makes the request without sending the hostnamenode.js http.get() 发出请求而不发送主机名
【发布时间】:2012-04-01 00:18:02
【问题描述】:

我有一些如下所示的 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 。是否有已知的原因可能会以这种方式运行?

【问题讨论】:

  • 还有options的价值是什么?

标签: http node.js


【解决方案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)来做这类事情。

【讨论】:

  • 最后它是我定义标题的方式中的一个 pb(当我将它从数组表示法 headers: [...] 更改为对象表示法 headers: {...} 时,它得到了修复
【解决方案2】:

您可能正在确认我在创建 http 请求的新样式时也遇到了一个错误。根据我的测试,我很确定这与在 http 标头/选项中设置内容类型有关。

我回到了旧的方式(即 http.createClient()),这很有效。所以这就是我的建议

【讨论】:

    猜你喜欢
    • 2019-06-25
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 2018-12-04
    • 2016-05-27
    • 1970-01-01
    • 2013-05-15
    • 2014-04-10
    相关资源
    最近更新 更多