I'm using NodeJS with Express middleware, and my only issue is to catch the exact Sent status Code to the response (for logs) in a global function.
Using the following code :
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const router = express.Router();
app.use(bodyParser.json());
router.get('/', (req, res, next) => {
// ..... SOME LOGIC
// Suppose that the variable content is coming from the DB
if (content.length === 0)
{
// Status Code : 404
res.send(404).send("The product cannot be found");
}
// Status Code : 200
res.json(content);
});
app.use((req, res, next) => {
// Problem : Always returns 200 !
console.log(res.statusCode);
next();
});
I am trying to catch all the requests, to log the status code in a middleware (app.use
), but my problem is that the res.statusCode
is always returning 200, even when I send myself a 404.
Question :
How can I catch the exact sent Status Code in a global function so that I can log it?
Thank you.