简体   繁体   中英

Retrieving the http.ServerResponse body

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?

Thehttp.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 aStream.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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM