Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express redirecting doesn't change req.url

I have a route that redirects upon successful login

app.post('/login', function(req, res){
  if(req.body.password === Server.cfg.auth.userPass) {
    req.session.user = {nick: req.body.username, pass: req.body.password}
    res.redirect('/chat')
  } else {
    res.render('user/login', { locals: { error: 'Invalid password' } })
  }
})

The redirect seems to work as the page is refreshed with the correctly rendered jade file. However, the url still says /login and my pageTitle variable (being set through template vars) does not change either. If I refresh the page after the redirect, everything changes to the way it should be. It is only after the redirect that it does not change.

like image 514
Pastor Bones Avatar asked Nov 14 '22 12:11

Pastor Bones


1 Answers

This has got to be a pretty common mix up for folks trying to deal with ajax redirects coming from a server controlled development background. My example shows what happens if authorization fails, slightly different; but you can use the same concept of intercepting the response and checking status, etc., and let the client JavaScript do the redirect.

My client code is actually a backbone model but in turn is calling jquery's ajax like:

model.save({ error:function... 

Server

function requiresLogin(req, res, next) {  
    if(req.session.user) {
        next();
    } else {
        //res.redirect('/sessions/new?redir=' + req.url); // won't work
        res.send("Unauthorized", 403); // send 403 http status
    }
}

Client

  // Assumes you can get http status from response
  error: function(resp, status, xhr)...
      if(resp.status === 403) {
          window.location = '/sessions/new'; // optionally put a redirLastPage=somewhere
      }

This works as desired for me. I'd also suggest googling ajax post redirects to see why this

like image 69
Rob Avatar answered Nov 16 '22 17:11

Rob