1

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

nvh
  • 95
  • 1
  • 6
  • does this answer your question? https://stackoverflow.com/a/29442079/8844451 – Naor Levi Jan 04 '22 at 11:41
  • Does this answer your question? [Node Express 4 middleware after routes](https://stackoverflow.com/questions/24258782/node-express-4-middleware-after-routes) – Naor Levi Jan 04 '22 at 11:41
  • No, I am trying to get the data send from `res.send(data);` in the middleware – nvh Jan 04 '22 at 11:45

2 Answers2

1

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();
});
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37
0

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();
});

nvh
  • 95
  • 1
  • 6