Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get response status code in a middleware

I am building an app in which I am trying to build my own logging system for each request.

For each request, I'd like to log the timestamp, the method used, the route, and finally the response code that has been sent to the client.

I have the following code for the moment :

// index.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.json());
app.use(cors());

app.use(require('./lib/logging'));

app.get('/', (req, res, next) => {
  res.send('hello world !');
});

app.listen(3001);

// ./lib/logging.js
const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  let code = chalk.yellow(res.statusCode); // Always 200
  log(`${now} ${method} request received on ${route} ${code}`);
  next();
}

Unfortunately, even if I do res.status(201).send('hello world') It will always catch a 200 status code... Is there a way to catch any response outgoing to the client and fetch its status code ?

like image 638
nook Avatar asked Jun 27 '18 09:06

nook


People also ask

How do I get a response status code?

To get the status code of an HTTP request made with the fetch method, access the status property on the response object. The response. status property contains the HTTP status code of the response, e.g. 200 for a successful response or 500 for a server error.

Can middleware be used in response?

Middleware functions can perform the following tasks: Execute any code. Make changes to the request and the response objects. End the request-response cycle.

What is RES statusCode?

The res. status() function set the HTTP status for the response. It is a chainable alias of Node's response. statusCode.

Can we use middleware in response in node JS?

With Node. js middleware, you can run any code and modify the request and response objects. You can also call for the next middleware in the stack when the current one is completed. The example below will help you with the process of creating your Node.


1 Answers

Using the finish event from the response was indeed the good solution. The problem was in the finish event callback, I just couldn't use the arrow function because it wouldn't bind the this keyword, and this is were was stored the response data.

So the following code is working :

// ./lib/logging.js

const moment = require('moment');
const chalk = require('chalk');
const log = console.log;

module.exports = (req, res, next) => {
  let now = `[${chalk.green(moment().format('HH:mm:ss'))}]`;
  let method = chalk.magenta(req.method);
  let route = chalk.blue(req.url);
  res.on('finish', function() {
    let code = chalk.yellow(this.statusCode);
    log(`${now} ${method} request received on ${route} with code ${code}`);
  })

  next();
}
like image 117
nook Avatar answered Sep 21 '22 23:09

nook