node.js - nodejs http.get响应中的body在哪里?

标签 node.js http

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

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

> res.finished
true

> res._hasBody
true

它已经完成了(http.get 会为你完成),所以它应该有一些内容。但是没有正文,没有数据,我无法从中读取。尸体藏在哪里?

最佳答案

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

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除了自动调用 req.end() 之外,它和 http.request 做同样的事情。

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

关于node.js - nodejs http.get响应中的body在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6968448/

相关文章:

javascript - 将元数据添加到 Stripe 客户对象

json - 使用 json 数据将 curl post 形成为 swift http post

.net - 在搜索表单中发布或获取?

javascript - 如何使用 node.js 检查文本文件中的重复行?

node.js - 从 super 账本结构获取 "Error: 8 RESOURCE_EXHAUSTED: Sent message larger than max (2217 vs. 15)"

debugging - 如何远程调试Lua?

http - 如何在 go-chi 中启用 gzip 压缩中间件

javascript - 为什么我的 API 调用会收到重复的数据,而这些数据本应是随机的?

c++ - 如何更新我的函数以使用新的 v8 FunctionTemplates?

node.js - Elasticdump 中的“现在无法切换到旧模式”错误