MrMangado
MrMangado

Reputation: 993

Issue with Express and middleware

function redit (req, res, next) {

 var session = req.session.user;

 if (session) {

    res.redirect('/home');

    next();

 }

 else {

    res.redirect('/');

    next();

 }

}

app.get('/', redit, function (req, res){

   res.render('home0.ejs');

}); 

I code this middleware to check if there's a req.session.user, if there is, the user would be redirected to home, if not, would be redirected to /. But when this middleware is called, Chrome says to me Error 310 (net::ERR_TOO_MANY_REDIRECTS)', any solutions...?

Upvotes: 0

Views: 943

Answers (1)

raina77ow
raina77ow

Reputation: 106453

You miss the fact that after redirect an anonymous user (with falsy req.session.user value) will end up at the same (/) page - so their identity will be checked up by redir middleware again... and again... and again. Hence the 'TOO MANY REDIRECTS' error.

The common solution is to redirect all the anonymouses to some other gateway page - and that page obviously should NOT check session.user.

Upvotes: 2

Related Questions