Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

express.js - how to intercept response.send() / response.json()

Lets say I have multiple places where I call response.send(someData). Now I want to create a single global interceptor where I catch all .send methods and make some changes to someData. Is there any way in express.js? (hooks, listeners, interceptors, ...)?

like image 354
pleerock Avatar asked Nov 16 '15 09:11

pleerock


People also ask

What does JSON () do in Express?

json() is a built-in middleware function in Express. This method is used to parse the incoming requests with JSON payloads and is based upon the bodyparser. This method returns the middleware that only parses JSON and only looks at the requests where the content-type header matches the type option.

How do I send a response in Express?

How to send a response back to the client using Express. In the Hello World example we used the Response. send() method to send a simple string as a response, and to close the connection: (req, res) => res.

What does Res send () do?

The res. send function sets the content type to text/Html which means that the client will now treat it as text. It then returns the response to the client.

What is Express () in express JS?

Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.


3 Answers

You can define a middleware as below (taken and modified from this answer)

function modifyResponseBody(req, res, next) {
    var oldSend = res.send;

    res.send = function(data){
        // arguments[0] (or `data`) contains the response body
        arguments[0] = "modified : " + arguments[0];
        oldSend.apply(res, arguments);
    }
    next();
}

app.use(modifyResponseBody);
like image 127
Sami Avatar answered Oct 05 '22 14:10

Sami


for those finding on google, based off the top answer:

app.use((req, res, next) => {
    const oldSend = res.send
    res.send = function(data) {
        console.log(data) // do something with the data
        res.send = oldSend // set function back to avoid the 'double-send'
        return res.send(data) // just call as normal with data
    }
    next()
})
like image 41
cpri Avatar answered Oct 01 '22 14:10

cpri


Yes this is possible. There are two ways to do this, one is to use a library that provides the interception, with the ability to run it based on a specific condition: https://www.npmjs.com/package/express-interceptor

The other option is to just create your own middleware (for express) as follows:

function modify(req, res, next){
  res.body = "this is the modified/new response";

  next();
}
express.use(modify);
like image 40
Don Avatar answered Oct 05 '22 14:10

Don