简体   繁体   中英

Nodejs redirecting issue as 'Error: Can't set headers after they are sent'

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.

After saving the new user, you try to redirect the user to '/users/all' . But at the end of your controller, you also try to render a page.

Your code probably succeeds creating the new user and tries to redirect, but before finishing that it receives a render page command as well. To fix the issue you should add

req.flash('success_msg', 'You created a new user');

res.redirect('/users/all');

return;

By including a return, you ensure to redirect the user and not to continue with the rest of the logic.

in newUser.save function you list err & doc inside function. doc isn't used in your if else statements after it. What's the point of doc, then?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM