Fast middleware before responding to customer

I need to change the response data that the module is sending to the client, as the module is using res.send

. I cannot figure out how I can change the data before it is executed to the client.

Is there any middleware / event I can use to catch res.send

and modify the data before it is executed?

I know it router.use

exists, but it is called before the function router.post

, not before it is sent to the res.send

client. So I need some kind of middleware router.post

that gets called after the function is done but before anything is sent to the client.

+3


source to share


3 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 a method end

), you'll have to override more functions ...

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

+7


source


The lack of code makes it difficult to answer your question, but you can use something like

Express 4.0:
router.use('/path', function (req, res) {
    // Modify req
});

      

.use

on the route will parse this before continuing on to the actual route, so if someone has submitted a form or whatever, it will hit in .use

before it goes to .post

or.get

Or you can do



Express 4.0:
app.use(function (req, res) {
    // Modify Req
    if (req.body.hasOwnProperty('some_form_name')) {
       // Do Somthing
    }
});

      

They are the same, but it will be called before every request for every route.

Not sure if this answers your question, but I think this might be what you are looking for?

0


source


Another solution:

https://community.apigee.com/questions/12183/usage-of-middleware-after-response-sent.html

expressApp.use (function (req, res, next) {req.on ("end", function () {console.log ('on request end');}); next ();});

0


source







All Articles