Randomblue
Randomblue

Reputation: 116413

Express response payload on response finish

I have an Express.JS server with many res.json. To perform statistics, logging and debugging, I want to capture the response payload in a catch-all hook.

I have found the finish event res.on('finish') but I cannot find how to extract the response payload from it.

Upvotes: 1

Views: 5350

Answers (2)

Baris Balli
Baris Balli

Reputation: 359

Express response object is extending native http server of the Nodejs

You can see in the link exact place where it is extending

And if you look at the official documentation of Nodejs you can see here that http server is listening on some events like connect, close and finish

Upvotes: 1

piemonkey
piemonkey

Reputation: 751

res.on('finish') is called once the data has been sent, so the payload doesn't necessarily exist on the server any more. You can add middleware to express to intercept every request and then override the .json method to log the data as the function is called:

router.use('/', (req, res, next) => {
  var old = res.json.bind(res);
  res.json = (body) => {
    //Do whatever
    old(body);
  }
  next();
})

Upvotes: 3

Related Questions