Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express middleware before response is carried out to client

I need to modify the response data a module sends to the client, as the module uses res.send i can't seem to figure out a way for me to modify the data before it's carried out to the client.

Is there any kind of middleware/event that I can use to catch the res.send and modify the data before its executed?

I am aware that router.use exists but it's called before the router.post function and not before the res.send is sent to the client. So I need some kind of middleware which is called after the router.post function is done but before anything is sent to the client.

like image 759
Sam Pettersson Avatar asked Jan 11 '15 08:01

Sam Pettersson


2 Answers

Well you can override the send function:

app.use(function (req, res) {
    var send = res.send;
    res.send = function (body) { // It might be a little tricky here, because send supports a variety of arguments, and you have to make sure you support all of them!
        // Do something with the body...
        send.call(this, body);
    };
});

If you want to support more than just calling send(like calling end method), then you have to override more functions...

You can check connect-livereload on how it adds a script to any html output.

like image 42
Farid Nouri Neshat Avatar answered Nov 16 '22 01:11

Farid Nouri Neshat


One more solution from here:

expressApp.use(function (req, res, next) {
    req.on("end", function () {
        console.log('on request end');
    });
    next();
});
like image 160
slava Avatar answered Nov 16 '22 01:11

slava