在bodyjs http.get响应中body是什么? [英] Where is body in a nodejs http.get response?

查看:712
本文介绍了在bodyjs http.get响应中body是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 http://nodejs.org/docs/ v0.4.0 / api / http.html#http.request ,但由于某种原因,我似乎无法在返回的完成的响应对象上实际找到body / data属性。

I'm reading the docs at http://nodejs.org/docs/v0.4.0/api/http.html#http.request, but for some reason, I can't seem to to actually find the body/data attribute on the returned, finished response object.

coffee> res = http.get({host:'www.somesite.com',path:'/'})

coffee> res.finished
true

coffee> res._hasBody
true

完成了(http.get就是这样)它应该有某种内容。但没有身体,没有数据,我不能读它。

It's finished (http.get does that for you), so it should have some kind of content. But there's no body, no data, and I can't read from it. Where is the body hiding?

推荐答案

http.request 文档包含如何通过处理数据事件接收响应正文的示例:

http.request docs contains example how to receive body of the response through handling data event:

var options = {
  host: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

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

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

http.get 的作用与http.request相同,只是它会自动调用 req.end()

http.get does the same thing as http.request except it calls req.end() automatically.

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

http.get(options, function(res) {
  console.log("Got response: " + res.statusCode);

  res.on("data", function(chunk) {
    console.log("BODY: " + chunk);
  });
}).on('error', function(e) {
  console.log("Got error: " + e.message);
});

这篇关于在bodyjs http.get响应中body是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆