I want to log every request with response information.
I tried to use middleware, and I have a problem.
res.body
is undefined.
app.use((req, res, next) => {
var time = Date.now();
res.on('finish', function() {
var clientIp = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
var method = req.method;
var path = req.baseUrl;
var duration = Date.now() - time;
console.log({
clientIp,
elapsedTime: `${duration}ms`,
hostname: req.headers.host,
level: 'INFO',
method,
path,
phase: process.env.NODE_ENV,
reqBody: req.body,
reqHeaders: req.headers,
resBody: res.body,
resHeaders: res.getHeaders(),
status: res.statusCode
});
});
next();
});
Actually there is response data on client.
How can I get response body in middleware?