Capturing response body in Express Middleware

Viewed 3827

I am trying to write a small API logger as an Express middleware. The logger collects various pieces of information from the req and res, then saves a JSON file to disk that can be read later.

This is my current function to store the logs.

function store(req, res, next) {
  init();

  const log = {
    request_url: req.hostname,
    request_body: req.body,
    request_method: req.method,
    request_headers: req.headers,
    api_endpoint: req.baseUrl,
    timestamp: moment().format('x')
  };

  res.on('finish', () => {
    log.response_body = res.body;
    log.response_status = res.statusCode;

    global.enoch_logs.push(log);

    fs.writeFile(`./logs/${ moment().format('x') }.json`, JSON.stringify(log), (err) => (err) ? console.log(err) : null);
  });

  next();
}

The problem is that res.body is always empty. I have tried a few different methods to capture the response body but nothing seems to work.

Where am I going wrong?

0 Answers
Related