节点js找不到响应主体http createserver

node js can't find response body http createserver

我是运行节点中的这个脚本:

var http = require('http');

var server = http.createServer(function (request, response) {
    response.writeHead(200, { "Content-Type": "text/plain" });
    response.write('Hello World\n');
    response.end('Goodbye World', 'utf8', function() {console.log(response.body);
    });

server.listen(8000);

console.log('running');

当我在 Chrome 中加载页面 (localhost:8000) 时,我看到:

Hello World

Goodbye World

到目前为止一切顺利,但我试图了解数据 ('Hello World/nGoodbyeWorld') 在响应对象中的位置。这就是为什么我将 'console.log(response.body)' 作为 response.end() 中的回调(节点 http 文档说回调将在响应完成流式传输时执行)。然而 console.log 只给出 'undefined'。当我 console.log 整个响应对象时,它 console.log 是响应对象,但我看不到其中的任何数据或正文,即使它有 'hasBody:true'.

所以问题是:

a) 有 response.body 吗?我认为必须有一个,否则浏览器中不会显示任何内容 window。 b) 如果可以,我该如何访问它,为什么我的方法不起作用?

我能找到的最接近的答案是这个:,但我尝试添加

 response.on('data', function(chunk) {
    body += chunk;
  });
  response.on('end', function() {
    console.log(body);
  });

,按照那里的建议,但没有用。还有人只是回答你如何访问数据,而不是为什么 response.body 不容易访问。

谢谢

没有响应主体,您写入响应流的数据只是在写入时发送给客户端(大部分)。将所有写入响应的内容都保存在内存中是没有意义的。

请求也是如此。如果需要,您必须自己缓冲传入的数据,这不是在幕后完成的,它只是流入。