In nodejs, I am facing one issue like 'Error: Can't set headers after they are sent' when I am trying to redirect after saving the form. The application used to get crash here.
Here is the code.
exports.createNewUser = function(req, res) {
var data = {};
data.title = 'All users';
if(req.method == 'POST'){
var firstName = req.body.firstName;
var lastName = req.body.lastName;
var email = req.body.email;
var gender = req.body.gender;
var mobile = req.body.mobile;
var address = req.body.address;
// Validation
req.checkBody('firstName', 'Firstname is required').notEmpty();
req.checkBody('lastName', 'Lastname is required').notEmpty();
req.checkBody('email', 'Email is required').notEmpty();
req.checkBody('email', 'Email is not valid').isEmail();
req.checkBody('mobile', 'Mobile is required').notEmpty();
req.checkBody('gender', 'Please choose you gender').notEmpty();
req.checkBody('address', 'Address is required').notEmpty();
req.checkBody('checkbox', 'You need to accept the terms').notEmpty();
var errors = req.validationErrors();
if(errors){
data.errors = errors;
}else{
var passwordGen = generator.generate({length: 10,numbers: true});
var newUser = new User({
firstName: firstName,
lastName:lastName,
email: email,
password: passwordGen,
mobile : mobile,
gender : gender,
address : address
});
// save user to database
newUser.save(function(err, doc) {
if (err) {
//console.error(err);
data.error = 'There are some error';
req.flash('error_msg', 'There are some error');
}else{
req.flash('success_msg', 'You created a new user');
res.redirect('/users/all');
}
});
console.log(data);
}
}
res.render('user/add', data);
};
Don't know what I am doing wrong here. Please help. Thank you.