I am trying to timeout a response back to the client if its taking too long on my server. But any solution I have found does not seem to trigger the timeout. This should timeout after 2 seconds, but for some reason my endpoint resolves with no timeout happening. Am I doing this correct?
app.use((req, res, next) => {
res.setTimeout(2000, () => {
console.log('Request has timed out.');
res.status(503).send('Service unavailable. Please retry.');
});
next();
});
// endpoints
...
// resolves after 5 seconds
app.get('/timeoutTest', (req, res) => {
const time = new Date().valueOf();
const futureTime = time + 5000;
while (new Date().valueOf() < futureTime) {
// nothing to do but wait
}
return res.status(200).send('5 seconds have passed since call');
});
res.setTimout
does not seem to be triggering if it has the next()
at the bottom of the middleware. However. If I comment out next()
it does trigger my res.setTimeout
after 2 seconds, but of course any http requests coming in wont get reached because there is no next()