1

I'd like to create some middleware that would log the request body and response body of all routes. Logging the request is straight forward, however, I can't seem to get the response. res.on('end') doesn't emit any data and I'm not seeing anything specifically tied into express that would emit or apply this. Would anyone have any suggestions how to achieve this?

EDIT: Based on the links in kook's answer, I've come up with this, which seems to work well.

app.use(function(req, res, next) {
    var send = res.send;
    res.send = function(body){
      console.log(body);
      res.send = send;
      res.send(body);
    };
    next();
});
dzm
  • 22,844
  • 47
  • 146
  • 226
  • Doesn't seem to wanna work. I've got mine set up as `app.use(/myroute, myroute); app.use(seeResDotSend)`. I have a `console.log` inside `seeResDotSend`, as the very first line, which fires fine. But then it doesn't seem to ever reach the `console.log` inside the `res.send = function(body) { ... }`. What am I doing wrong? – SeriousLee Jan 16 '19 at 17:34

1 Answers1

0

Have you seen these posts about similar? I think you should be able to follow their logic in creating your own:

express logging response body

Node.Js/ Express - simple middleware to output first few characters of response

Community
  • 1
  • 1
k00k
  • 17,314
  • 13
  • 59
  • 86