【问题标题】:what is wrong with my http request我的 http 请求有什么问题
【发布时间】:2015-05-18 23:13:29
【问题描述】:

我可以在浏览器中输入我的 url : 192.168.1.132 并得到“hello world”的正确响应,如果我执行 curl 192.168.1.132 也是如此

但是如果我运行这段代码

var http = require('http');

var options = {
  host: 'http://192.168.1.132',
  path: '/'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
  console.log(str);

我得到错误:

events.js:85
      throw er; // Unhandled 'error' event
            ^
Error: getaddrinfo ENOTFOUND http://192.168.1.132
    at errnoException (dns.js:44:10)
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:94:26)

我做错了什么?

【问题讨论】:

  • 主机不应包含协议;只是192.168.1.132
  • 没有协议,我得到类似的错误 events.js:85 throw er; // 未处理的 'error' 事件 ^ 错误:在 Socket.emit (events.js:107:17) 在 readableAddChunk (_stream_readable.js: 163:16) 在 Socket.Readable.push (_stream_readable.js:126:10) 在 TCP.onread (net.js:529:20)

标签: node.js http request


【解决方案1】:

从您显示的代码中可以看出的唯一错误是在您的options 对象的host 属性中包含协议方案。那应该是:

host: '192.168.1.132',

更改后出现的任何其他错误都在您未显示的代码中。这是基于您的代码的工作代码示例。

var http = require('http');

var options = {
  host: 'www.google.com',
  path: '/index.html'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });
};

var req = http.request(options, callback);

req.on('error', function (e) {
  console.log('problem with request: ' + e.message);
});

req.end();

【讨论】:

  • trott,我在没有协议的情况下使用编辑过的主机尝试了您的代码,但出现“解析错误” ") 输出是否需要采用某种格式?
猜你喜欢
  • 1970-01-01
  • 2015-11-30
  • 2019-09-02
  • 1970-01-01
  • 1970-01-01
  • 2013-11-20
  • 1970-01-01
  • 1970-01-01
  • 2016-09-01
相关资源
最近更新 更多