The title should be pretty self explanetory.
For debugging purposes, I would like express to print the response code and body for every request serviced. Printing the response code is easy enough, but printing the response body is trickier, since it seems the response body is not readily available as a property.
The following does NOT work:
var express = require('express'); var app = express(); // define custom logging format express.logger.format('detailed', function (token, req, res) { return req.method + ': ' + req.path + ' -> ' + res.statusCode + ': ' + res.body + '\n'; }); // register logging middleware and use custom logging format app.use(express.logger('detailed')); // setup routes app.get(..... omitted ...); // start server app.listen(8080);
Of course, I could easily print the responses at the client who emitted the request, but I would prefer doing at the server side too.
PS: If it helps, all my responses are json, but hopefully there is a solution that works with general responses.
To log the response body with Express, we can create our own middleware to intercept the response and log it. const logResponseBody = (req, res, next) => { const oldWrite = res. write const oldEnd = res. end; const chunks = []; res.
The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.
Not sure if it's the simplest solution, but you can write a middleware to intercept data written to the response. Make sure you disable app.compress()
.
function logResponseBody(req, res, next) { var oldWrite = res.write, oldEnd = res.end; var chunks = []; res.write = function (chunk) { chunks.push(chunk); return oldWrite.apply(res, arguments); }; res.end = function (chunk) { if (chunk) chunks.push(chunk); var body = Buffer.concat(chunks).toString('utf8'); console.log(req.path, body); oldEnd.apply(res, arguments); }; next(); } app.use(logResponseBody);
I ran into an issue using the approach suggested by Laurent. Sometimes chunk is a string, and therefore causes problems in the call to Buffer.concat(). Anyways, I found a slight modification fixed things:
function logResponseBody(req, res, next) { var oldWrite = res.write, oldEnd = res.end; var chunks = []; res.write = function (chunk) { chunks.push(new Buffer(chunk)); oldWrite.apply(res, arguments); }; res.end = function (chunk) { if (chunk) chunks.push(new Buffer(chunk)); var body = Buffer.concat(chunks).toString('utf8'); console.log(req.path, body); oldEnd.apply(res, arguments); }; next(); } app.use(logResponseBody);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With