Reputation: 160
I have a nodejs app which is using express.
For a specific GET request, I would like to set a timeout, and if this timeout is reached, then I would like to completely end the request and redirect to a timeout page.
I tried the following in my route.js file :
app.get('/exec', isLoggedIn, function(req, res) {
var customTimeout = 10000;
req.connection.setTimeout(customTimeout, function(){
console.log("TIMED!");
res.render('timeout.ejs', {
user: req.user,
});
});
//execution of the GET request
res.render('success.ejs', {
user: req.user,
});
});
After 10 seconds, I can see the "TIMED!" message in the logs, but I'm not redirected to the timeout page, and the request is still running in the background...
Can someone help me deal with this ?
Upvotes: 1
Views: 3009
Reputation: 203286
This works for me:
app.get('/exec', isLoggedIn, function(req, res) {
var customTimeout = 10000;
res.setTimeout(customTimeout, function(){
console.log("TIMED!");
res.render('timeout.ejs', { user: req.user });
});
res.render('success.ejs', { user: req.user });
});
I'm assuming that instead of the last res.render()
, you're executing some sort of operation that may take a lot of time to finish (and after 10 seconds you want to notify the user that the operation timed out).
If that operation isn't cancellable somehow, eventually it will finish and also try to send back a response, in which case you can run into errors (most likely "Can't set headers after they are sent").
So before sending a response, you need to check if one hasn't been sent already by the timeout handler. You can use res.headersSent
for that.
Upvotes: 3