vkstack
vkstack

Reputation: 1664

how to set cookie before sending response node js (Sails)

I am having a problem if the cookie will be set before the the response is being sent. like i want to set cookie for logged in user and then i want to send the response OK.

User.find({user:req.body.username,password:req.body.password})
  .exec(function(err,row){
  if(err){
    console.log(err);
    res.negotiate();
  }
  else if(row.length){
    res.cookie('user',{user:row[0].user,role:row[0].role},{
      signed:true,
      httpOnly:true,
      maxAge:1000*60*60*24*5
    });
    res.end('You are logged in successfully');
  }
  else{
    console.log('nothing executed');
    res.end('Not such a user');
  }
});

is it sure that the res.cookie() will be executed before res.end()

Upvotes: 1

Views: 2653

Answers (1)

Petko Bossakov
Petko Bossakov

Reputation: 540

You "set" a cookie by sending a Set-Cookie header to the browser. Therefore, strictly speaking, it is not possible to set a cookie before sending a response. Calling res.cookie() just prepares the respective header but does not actually send it.

I see you use cookies to store user data, so in this case you might be better off using a session module like https://github.com/expressjs/session -- it will let you read or write data at any time and handle the low-level cookie business for you.

Upvotes: 2

Related Questions