35

For some reason I cant redirect to /blog once my login is completed. In my login controller I have the following.

module.exports = {

    post: function(req, res) {
         var login = req.body['login'];                      

         if (login && req.body['login']['password'] == "password") {
            console.log('Granted access');
            res.send({redirect: '/blog'});

         }

         else {
             console.log('wrong password');
             res.redirect('back');

         }

    }

};

The jquery ajax

$(document).ready ->

    $('#login-button').click () ->

        $.ajax
            url: '/login'
            type: 'POST'
            data: $('#Password').serialize()
            dataType: 'json'
            success: (data, textStatus, jqXHR) ->
                if typeof data.redirect == 'string'
                    window.location = data.redirect

updated to working code

lostAstronaut
  • 1,331
  • 5
  • 20
  • 34
  • Can you tell us exactly what it is doing? What response code do you get? For one thing, you need to set up your middleware (`app.use(express.bodyParser())`) during initial app load, not during each request process. – Peter Lyons Jul 20 '12 at 00:51
  • I updated it. I'm not getting any response at all and I have app.use(express.bodyParser()) in my app load inside server.js – lostAstronaut Jul 20 '12 at 01:01
  • You are generating a 200 response code, so you must be getting a response, perhaps with an empty body though. Are you sure the login controller's `post` function is being called? Do you see the output from those `console.log` statements? Given your if/else, in any case you are calling `res.redirect` so you should be getting a 301 response code. This leads me to believe it's a different route handler entirely that is responding to the request. – Peter Lyons Jul 20 '12 at 02:09
  • Yes this is the result to console.log which displays before hand. updated above – lostAstronaut Jul 20 '12 at 02:17
  • Now I am getting a 304 response code – lostAstronaut Jul 20 '12 at 02:23
  • Could the Problem be that I need to change from my login.js controller to my blog.js controller. – lostAstronaut Jul 20 '12 at 03:09
  • That 304 most likely means that the redirect happened, but to a URL handled by `express.static` which is saying "I already sent this to you." What comes after the part of the server file you showed us? – ebohlman Jul 20 '12 at 03:27
  • So it looks like the `res.redirect` is actually working, so you respond with a 301 status code and `Location` header of `/blog`, so the browser does the `GET /blog` which we see in the log. I think the login itself is working but the subsequent GET /blog is not doing what you intend. – Peter Lyons Jul 20 '12 at 04:32
  • That's good, I'll stop messing with the res.redirect. How to I fix the GET /blog – lostAstronaut Jul 20 '12 at 04:42

3 Answers3

71

You can't make a redirection after an AJAX. You need to do it yourself in Javascript.

server

post: function(req, res) {
     var login = req.body['login'];          
     app.use(express.bodyParser());


     if (login && req.body['login']['password'] == "tom") {
        var loginPassword = req.body['login']['password'];
        console.log(loginPassword);
        console.log('Granted access');
        res.send({redirect: '/blog'});

     }

     ...

}

client

$(document).ready ->
    $('#login-button').click () ->
        $.ajax
            url: '/login'
            type: 'POST'
            data: $('#Password').serialize()
            dataType: 'json'
            success: (data, textStatus, jqXHR) ->
                if typeof data.redirect == 'string'
                    window.location = data.redirect

This should work.

Charles
  • 11,367
  • 10
  • 77
  • 114
  • Thanks man that worked, one question. Can you redirect from the server? Say I get to blog and the session cookie doesn't check out. Can you redirect back to login via res.redirect or something else. – lostAstronaut Jul 20 '12 at 14:09
  • Thanks for the reply. I was banging my head for 3 days as to why it is not working from ajax but from browser hits. – Tarun Oct 26 '16 at 11:07
4

POSTs are redirected to GETs. You can't redirect to a POST to a POST; you could forward it but that would be weird. I recommend adding logic to your GET route that will handle a logged in versus not logged in user.

Also, 304 likely means your response is being cached by your browser because you used a 301 (permanent redirect, very bad on login, etc.; use 302).

cjohn
  • 11,370
  • 3
  • 30
  • 17
  • 4
    I realize this quite old, but it's worth mentioning that a `res.redirect(307, '...path')` will in fact preserve the method. A POST will be redirected with POST as the method, – Seth Webster Apr 29 '19 at 18:34
-4

You are missing return:

return res.redirect('/');
Badacadabra
  • 8,043
  • 7
  • 28
  • 49