如何从node.js中获取请求的响应中获取数据?

时间:2013-12-06 10:20:50

标签: javascript node.js get

尝试使用express模块​​从node.js获取请求。这是这篇文章的代码:

var req = http.request(options, function(res) {
    res.on('data', function (chunk){
    });

});
req.end();

但无法理解如何从响应主体接收数据,我试过res.body。或res.data。没用。

1 个答案:

答案 0 :(得分:2)

数据到达chunk参数。无论如何它的一部分。您需要选择并将所有块加入到完整的响应中。来自http://docs.nodejitsu.com/articles/HTTP/clients/how-to-create-a-HTTP-request的复制粘贴示例:

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
  host: 'www.random.org',
  path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};

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

http.request(options, callback).end();