Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express sendfile and redirect url

I have a bunch of middleware. At the first app.use I test if the process is under duress, and if so I want it to just send the static /index.html file and redirect the user's browser to "/#" + req.url.

for example:

app.set("port", PORT)
//etc
app.use(function(req, res, next) {
  if (something)
    res.sendfile('/public/index.html', { root: __dirname + '/..' })
    // also, redirect the user to '/#' + req.url
  else
    next()
});
// a ton more middleware that deals with the main site
app.use(express.static(...))

Right now, it just sends the index.html to whatever url they're at. How can I redirect them to "/" and serve index.html without messing up any future middleware.

like image 431
switz Avatar asked Nov 22 '25 11:11

switz


1 Answers

Not sure if I understand correctly, but try this:

app.use(function(req, res, next) {
  if (something && req.path !== '/')
    return res.redirect('/');
  next();
});

app.get('/', function(req, res, next) {
  if (something)
    return res.sendfile('/public/index.html', { root: __dirname + '/..' });
  next();
});

app.use(express.static(...));
like image 90
robertklep Avatar answered Nov 23 '25 23:11

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!