Rishi
Rishi

Reputation: 143

Is there any way to monitor every response in Express.js?

I want to create a middleware function in express.js. which can monitor every requests and responses. I created a middleware but it can only monitor the requests, not the responses.

function middlewareFunc (req,res,next) {
  console.log(req.body , req.params , req.query);
  next();
}

Upvotes: 2

Views: 2435

Answers (3)

BlackMamba
BlackMamba

Reputation: 10254

You should know that res in function(req, res, next) is a instance of class http.ServerResponse. So it can be listen on finish event, please see the link: https://nodejs.org/api/stream.html#stream_event_finish

app.use(function (req, res, next) {
    function afterResponse() {
        res.removeListener('finish', afterRequest);
        res.removeListener('close', afterRequest);

        // action after response
    }

    res.on('finish', afterResponse);
    res.on('close', afterResponse);

    // action before request
    // eventually calling `next()`
});

app.use(app.router);

app.use() and middleware can be used for "before" and a combination of the close and finish events can be used for "after."

Upvotes: 5

Mukesh Sharma
Mukesh Sharma

Reputation: 9022

For that you can write two middlewares

1) Before all request endpoints.

//middleware
function middlewareFunEarlier(req,res,next) {
   console.log(req.body , req.params , req.query);
   next();
}

app.use(middlewareFunEarlier);

app.get('/', function(req, res, next){
   //do something
   res.end();
});

2) After all end points. And you must have to use next() in all endpoints

app.get('/', function(req, res, next){
   //do something
   next();
});

app.use(middlewareFunLater);

//middlware

function middlewareFunLater(req, res, next){
   console.log(res);
   res.end();
}

It can be work around with existing tools.

Upvotes: 2

user3210475
user3210475

Reputation: 9

Ok, so first of all, the reason you are only seeing the requests is because of how middleware works. Everything gets run once in a certain order, and runs only once. When your middleware gets run it is most likely before the response has been created. In order to get the response you would have to make your code run when your controller goes to render or something like that.

Second of all, it seems like basic logging is all you need.(weather it be with a library or just console logging stuff.)

Upvotes: 0

Related Questions