节点js找不到响应正文http createserver [英] node js can't find response body http createserver

查看:144
本文介绍了节点js找不到响应正文http createserver的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在节点中运行此脚本:

I am running this script in node:

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)时,我看到:

When I load the page (localhost:8000) in Chrome I see:

Hello World

Hello World

再见世界

到目前为止,一切都很好,但是我试图了解数据("Hello World/nGoodbyeWorld")在响应对象中的位置.这就是为什么我将'console.log(response.body)'作为response.end()中的回调(节点http文档说该回调将在响应完成流式传输后执行)的原因.但是console.log只是给出未定义".当我用console.log记录整个响应对象时,它会用console.log记录响应对象,但是即使其中有"hasBody:true",我也看不到其中的任何数据或正文.

So far so good, but I'm trying to understand where in the response object the data ('Hello World/nGoodbyeWorld') is. That's why I have 'console.log(response.body)' as the callback in response.end() ( the node http documentation says that the callback will be executed when the response has finished streaming). However the console.log just gives 'undefined'. When I console.log the whole response object it console.logs the response object ok but I can't see any data or body in there even though it has 'hasBody:true'.

所以问题是:

a)是否有response.body?我认为必须有一个,否则在浏览器窗口中什么也不会显示. b)如果可以,我该如何访问它?为什么我的方式不起作用?

a) is there a response.body? I am thinking there has to be one otherwise nothing would show in the browser window. b) if so how can i access it and why doesn't my way work?

我能找到的最接近的答案是这个:在哪里是在nodejs http.get响应中?,但是我尝试添加

The closest answer i could find was this one: Where is body in a nodejs http.get response? , but I tried adding

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

,如那里的建议,它不起作用.另外,人们只是在回答如何访问数据,而不是为什么响应.body难以访问.

, as suggested there and it didn't work. Also people there are just answering HOW you can access the data, not WHY the response.body isn't easily accessible.

谢谢

推荐答案

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

There is no response body, the data you write to the response stream is just sent to the client as you write it (for the most part). It wouldn't make sense to keep in memory everything ever written to the response.

请求也一样.如果需要,您必须自己缓冲传入的数据,它不是在后台完成的,只是流进来的.

The same goes for requests. You have to buffer the incoming data yourself if you want that, it is not done behind the scenes, it is merely streamed in.

这篇关于节点js找不到响应正文http createserver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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