1

I have built an api and i would like to log all of the requests and responses made.

I have a route GET: api/transactions

In this route i return the following response. This wrapper response is quite common throughout my application.

return res.status(200).json({
    success: true,
    status: 200,
    data: transaction,
    message: "Successfully retrieved transaction",
});

I have a middleware that is dealing with creating log entries. Inside the res.on("finish") event i want to access the json data i am returning above.

app.use(responseTime((req, res, time) => {

            res.on("finish", () => {

                // console.log(res);

                const responseLog = {
                    log_id: logId,
                    line_data_statusCode: res.statusCode,
                    line_data_statusMessage: res.statusMessage,
                    line_data_responseTime: time,
                    message: ".", // get res json message
                };

                this.log.info({ ...responseLog, ...{ log_type: "response" } });

            });

        }));

How can i access the res data from the event.

mihai
  • 37,072
  • 9
  • 60
  • 86
Kay
  • 17,906
  • 63
  • 162
  • 270
  • `message:res.json()` should work – Mahesh G Sep 12 '18 at 15:57
  • @Ron res.json() just returns back res. like this - https://pastebin.com/MWAsYtwS – Kay Sep 12 '18 at 16:00
  • I think the body is sent asynchronously before and you have to collect the chunks from the `data` events, then log them on `finish` or `end` like this: https://stackoverflow.com/questions/19215042/express-logging-response-body – Benno Sep 12 '18 at 16:08
  • Possible duplicate of [express logging response body](https://stackoverflow.com/questions/19215042/express-logging-response-body) – Lawrence Cherone Sep 21 '19 at 16:38

0 Answers0