http - node.js http.get() 发出请求而不发送主机名

标签 http node.js

我有一些如下所示的 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/

相关文章:

javascript - Electron 网模块需要很长时间才能得到响应

http - 提供大型视频文件失败

mysql - 自动数据库迁移 (MysQl)

javascript - 节流、多个客户端请求、Node js 中的 Express 线程

node.js - HTTP 重定向到不同端口的 HTTPS

java - Android 的 HttpURLConnection 在 HEAD 请求上抛出 EOFException

python - python -m http.server 可以配置为处理并发请求吗?

node.js - 如何结合 Winston 和 pm2 进行按特定计划轮换的日志记录

javascript - 更新给定索引的数组值(mongoose,mongodb)

html - Browserify 需要 ('fs' )