I am working on a NODE JS project with Typescript started by other people and I need to trigger an action if the response from some endpoints is successful, so I need to intercept this response before it is sent to the entity that is making the request.
The request is made, first it goes through anothers middlewares, then it goes to the controller, when it finishes, I need to catch it.
The way the responses are returned from controllers is this
return response.status(200).json(data);
How can I solve this issue?
CodePudding user response:
You can add some middleware BEFORE any of your request handlers that send a response that monitors the finish
event on the response stream object to track when the request is done:
app.use((req, res, next) => {
// listen for when the request is done
res.on('finish', () => {
console.log(`request for ${req.url} finished with status ${res.statusCode}`);
});
next();
});