Home > Software engineering >  Express: Get the data sent on finish
Express: Get the data sent on finish

Time:01-05

I would like to create and express.use a middleware that gets the data sent from all endpoints and use it for caching. But I am unable to get that data with res.on('finish', cb). Is there even such a thing ?

Thank you

CodePudding user response:

I will close my question since I found a way myself :

app.use((req, res, next) => {
  const send = res.send;

  res.send = (data) => {
    res.send = send; // this line is important not to have an infinite loop

    // do something with `data`

    return res.send(data);
  };

  next();
});

CodePudding user response:

Add middleware and override existing res.send function with your custom function like below

app.use((req, res, next) => {
  const { send } = res;
  res.send = (data) => {
    // Store in cache
    return send(data);
  };
  next();
});
  •  Tags:  
  • Related