1

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

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

Hello World

Goodbye World

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'.

So the question is:

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?

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

, 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.

Thanks

Community
  • 1
  • 1
Sam Rae
  • 61
  • 10
  • 2
    `response` is a special type of stream object. When you write to the stream, the data is managed by the stream and eventually sent as part of an http response over TCP to the client. There is no `response.body` that contains everything that has been sent. You can read about it's various methods [here](https://nodejs.org/api/http.html#http_class_http_serverresponse). – jfriend00 Feb 07 '16 at 00:12
  • 1
    The `response` object you see in the *server* code is a stream that you are writing into. The [other question you found](https://stackoverflow.com/questions/6968448/where-is-body-in-a-nodejs-http-get-response) discusses how the response looks in the client code - it's a stream where you can read from. – Bergi Nov 12 '19 at 01:34
  • i answered a similar question here https://stackoverflow.com/questions/73481163/nodejs-getting-raw-https-request-and-response – matt richards Aug 27 '22 at 10:44

1 Answers1

3

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.

mscdex
  • 104,356
  • 15
  • 192
  • 153