Home > Enterprise >  Modify response before it is sent to client
Modify response before it is sent to client

Time:11-04

Node 16.14.2, Express 4.18.1

I've seen plenty of people modifying res.send to perform actions before the response is sent to the client.

app.use(function (req, res, next) {
    originalSend = res.send;
    res.send = function (body) {
        // Do something with the body...
        originalSend.call(this, body);
    };
    next();
});

However, if I send data other than 'body', it result in some error.

originalSend = res.send;

res.send = function (body) {
    originalSend.call(this, body);
    // Works fine

    originalSend.call(this, { ...body, "USER": req.user });
    // RangeError: Too many properties to enumerate

    originalSend.call(this, {})
    // RangeError: Maximum call stack size exceeded

    originalSend.call(this, { "Foo": "bar" })
    // RangeError: Maximum call stack size exceeded
}

I've tried pretty much everything, 'body' is the only thing that will go through, how come ?


UPDATE:

Seems like converting the data to a string solved the problem.
I still don't know why there was a problem in the first place since send is supposed to be able to handle objects and other types of data (which works fine outside this function definition in my app).

originalSend.call(this, JSON.stringify({ ...body, "Foo": "bar" }));

CodePudding user response:

Here is the working code:

const originalSend = res.send;
res.send = function (body) {
    // Do something with the body...
    originalSend.call(this, JSON.stringify({ ...JSON.parse(body), 'USER': 'user' }));

    //console.log(typeof body)
};

Reason:

body param in the function has string type. That means originally the res.send call accepts only string value. So to combine your custom values with dynamic response, you have to convert body to JSON and then convert the entire 2nd param to call to stringified object.

  • Related