I am new to node land and I have a case like below where I first want to set a cookie and then redirect to other url. But I get the error - Unhandled rejection Error: Can't set headers after they are sent
.
user_details = [req.body.user_name, req.body.user_email, req.body.user_contact, req.body.route_id];
var user_details_str = JSON.stringify(user_details);
res.cookie('user_details', user_details_str, {maxAge : 7 * 24 * 3600000, httpOnly:false});
res.redirect('/route1');
I went through this Node.js Error: Can't set headers after they are sent and understood that res.redirect()
is trying to rewrite the header but don't know how to solve this issue.
EDIT : Complete code.
router.post('/register', encryptor.encryptUserPassword, function(req, res, next) {
req.body.confirmed = false;
Models.users.create(req.body).then(function(user) {
user_details = [req.body.user_name, req.body.user_email, req.body.user_contact, req.body.route_id];
var user_details_str = JSON.stringify(user_details);
res.cookie('user_details', user_details_str, {maxAge : 7 * 24 * 3600000, httpOnly:false});
user.user_pass = '';
sess = res.session;
// sess.email = user.user_email;
Models.user_ride.create({user_id:user.user_id,route_id:req.body.route_id}).then(function(userroute){
res.send(user);
});
res.redirect('/route1');
}).error(function(err) {
res.send(err);
}).catch(Sequelize.ValidationError, function(err) {
res.send(err);
});
});