D
D
Danil2014-12-23 18:04:15
JavaScript
Danil, 2014-12-23 18:04:15

Why is the cookie inactive at the time of my request?

Sending a request:

(function(){
  
  $('body').on('click', '.enter', function() {
    
    var username = $('.login').val(),
      password = $('.password').val();
    
    var data ={
        'username': username,
        'password': password
        };
    	
    $.ajax({
      type: "POST",
      url: 'login',
      data: data,
      success: window.location.href = 'main'
  });
    
  });
  
})();

My login.js file which handles all this is:
connection.query('SELECT password FROM `users` WHERE login = "' + username +'"', function(err, rows, fields) {
    if (err) throw err;
    else if (rows.length > 0 && password == rows[0].password) {
      console.log('Hello');
      res.cookie('cookie', 'superseecret', { maxAge: 43200, httpOnly: true, signed: true })
      res.end();
    } else {
      console.log('Go away!');
      res.end();
    }
  });

And here I render a new page after the client callback fires:
router.get('/main', function(req, res) {
  if (req.signedCookies.cookie == 'superseecret') {
    res.render('main', { asd:seecretData });
  } else {
    res.send('Go away!');
  }
});

But when the user gets to / main there he sees Go away!, although there are cookies in the browser. If you refresh the page, then everything is fine. As far as I understand - processing / main starts faster than the cookie is written. But how is this possible if I redirect to /main after I receive a succsess callback?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Power, 2014-12-23
@Veneomin

You

{
  success: window.location.href = 'main'
}

is executed immediately, but should be wrapped in a function:
{
  success: function() { window.location.href = 'main'; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question