I need to define a timeout for specific routes in Express so that instead of getting a server default timeout error, my API returns JSON data. I add it like this to the beginning of the router.get callback function
router.get('/', function (req, res, next) {
res.setTimeout(10000, function () {
res.status(500).json({ error: 'Response Processing Timed Out.' });
});
/*
some time-consuming code here
*/
res.json(result); //this should never happen if timeout occurs
});
and that (timeout part) works OK (it returns JSON error message to the client on timeout, as expected).
The problem is that the rest of the code is still executed and when it gets to the regular res.json method - res.json(result) I get the error ERR_HTTP_HEADERS_SENT (as it should be, because it tries to do another res.json after the one containing the error message has already been sent)
If that was an ordinary check for errors I would add a return statement after res.json, but it is not - it is inside a callback function and a return would just end the callback, but not the parent function (in this case router.get callback function). I know that I could set some variable to true when timeout occurs and then check if it is true before any res.json, but I'd like to avoid that (I have quite a few res.json lines in the function, and also I'd like to avoid executing time-consuming code if the error message has already been sent)
Any ideas on how to solve this? If res.setTimeout is not the proper way, I'll be glad to learn the right way to do this.
Thanks