2

I want to customise the response sent to the users when a timeout error is fired. More specifically, I want to redirect them to a static page explaining why a timeout error has been fired.

I want to write something like :

var express = require('express')
var timeout = require('connect-timeout')
var app = express();

var port = process.env.PORT || 8080;

app.use(timeout(10,{"respond":true}));
app.use(haltOnTimedout);

// GET ROUTES HERE

app.listen(port, function() {
    console.log('Our app is running on port '+ port);
});

function haltOnTimedout(req,res,next) {
    if (req.timedout) {
        res.redirect('/timedout.html');
    } else {
        next();
    }
};

The code above is not working as intended : even if a timeout is fired, it does not redirect the user to the static webpage timedout.html, instead it throws the error ServiceUnavailableError: Response timeout

Is it possible to do something like this or am I missing something ?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
ldc
  • 306
  • 1
  • 14
  • What exactly is not working? And which express version are you using? For express version 3 and lower you can import `timeout` with the following code: `var timeout = express.timeout;` – mrunde Oct 19 '16 at 10:30
  • Sorry, I forgot *not* in : "it does **not** redirect the user to the webpage", see the edited question. I'm using Express 4.10.2 – ldc Oct 19 '16 at 11:53

1 Answers1

1

I finally find the answer and post it here if someone get the same question.

I placed the following line of code at the very end of my server.js code :

app.use(haltOnTimedout);
function haltOnTimedout(err,req,res,next) {
    if (req.timedout === true) {
        if (res.headersSent) {
            next(err);
        } else {
            res.redirect('/timedout.html');
        }
    } else {
        next();
    }
};

and add if (!req.timedout) { res.send(something);} in all routes in order to avoid double send of the headers.

ldc
  • 306
  • 1
  • 14