我的http请求有什么问题

时间:2015-05-18 14:39:45

标签: node.js http request

我可以输入我的网址:192.168.1.132到我的浏览器中,我得到了“hello world”的正确回复,如果我做了卷曲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)

我做错了什么?

1 个答案:

答案 0 :(得分:0)

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

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();