1

I need to retrieve the body of a http.ServerResponse. Since it's a stream I assumed that I simply could add a response.on("data", function(){}) to retrieve the stream chunks. I put together a simple nodeJS http server.

const http = require('http');

http.createServer((request, response) => {

  response.on("data", function(){
    console.log("data",arguments)}
  );
  response.on("end", function(){
    console.log("end",arguments)
  });
  response.on("finish", function(){
    console.log("finish", arguments)
  });

  let body = [];
  request.on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    response.end(body);
  });
}).listen(8080);

Once started, I invoke it with a simple curl call.

curl -d "echo" -X POST http://localhost:8080

It turn's out that the data event isn't triggered. I didn't find any other way of getting the body via response object. How can I do that?

Stan Wiechers
  • 1,962
  • 27
  • 45

2 Answers2

2

The http.ServerResponse is for sending data back to the client. This extends the base Stream which does not include any events, but is an EventEmitter. The http.ServerResponse stream only has the 'close' and 'finish' events as documented.

To read the body of an incoming request, you use the first parameter, the http.IncomingMessage, which is a Stream.Readable and has a 'data' event.

const http = require('http');

http.createServer((request, response) => {

  request.on("data", function(){
    console.log("data",arguments)}
  );
  request.on("end", function(){
    console.log("end",arguments)
  });
  request.on("close", function(){
    console.log("close", arguments)
  });

  let body = [];
  request.on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    response.end(body);
  });
}).listen(8080);
theusaf
  • 1,781
  • 1
  • 9
  • 19
1

Found a solution. Overriding the write method, intercepting the data and then calling the original method.

const http = require('http');

http.createServer((request, response) => {

  let original = response.write
  const chunks = [];

  response.write = function(chunk, encoding, callback){
    chunks.push(chunk)
    original.apply(response,arguments);
  }

  //when using express
  response.send = function(chunk, encoding, callback){
    chunks.push(chunk)
    originalSend.apply(response,arguments);
    response.end()
  }

  response.on("finish", () => {
    console.log("body",chunks.toString())
  });




  let body = [];
  request.on('data', (chunk) => {
    body.push(chunk);
  }).on('end', () => {
    body = Buffer.concat(body).toString();
    response.write("OK");
    response.end();
  });
}).listen(8080);
Stan Wiechers
  • 1,962
  • 27
  • 45