Created
November 14, 2017 21:12
-
-
Save mrmccormack/b1d5f9021281f3d2a20b38bce794c6b2 to your computer and use it in GitHub Desktop.
Expressjs / Nodejs Error: Can't set headers after they are sent.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* POST /signup | |
* Create a new local account. | |
*/ | |
// TODO: if you try existing email and exist. username, this will trigger an errors | |
// Error: Can't set headers after they are sent. | |
// not sure why this happens, it works sometimes | |
exports.postSignup = (req, res, next) => { | |
req.assert('email', 'Email is not valid').isEmail(); | |
req.check('username', 'username must be 6-50 lower case characters, only letters and numbers, no spaces allowed.').isAlphanumeric().isLowercase().len(6); | |
req.sanitize('email').normalizeEmail({ | |
gmail_remove_dots: false | |
}); | |
const errors = req.validationErrors(); | |
if (errors) { | |
req.flash('errors', errors); | |
return res.redirect('/signup'); | |
} | |
const user = new User({ | |
email: req.body.email, | |
username: req.body.username, | |
// password: req.body.password | |
}); | |
User.findOne({ | |
email: req.body.email | |
}, (err, existingEmail) => { | |
if (err) { | |
return next(err); | |
} | |
if (existingEmail) { | |
req.flash('errors', { | |
msg: 'Account with that email address already exists.' | |
}); | |
return res.redirect('/signup'); | |
} else { | |
User.findOne({ | |
username: req.body.username | |
}, (err, existingUser) => { | |
if (err) { | |
return next(err); | |
} | |
if (existingUser) { | |
req.flash('errors', { | |
msg: 'Account with that username name already exists.' | |
}); | |
return res.redirect('/signup'); | |
} else { // if here... then unique email and unique username, so save it | |
user.save((err) => { | |
if (err) { | |
return next(err); | |
} | |
req.logIn(user, (err) => { | |
if (err) { | |
return next(err); | |
} | |
// doesn't wokr either res.redirect('/account'); | |
return res.redirect('/account'); | |
// res.redirect('/account'); | |
}); | |
}); // end user.save function | |
} // end else if existing user | |
}); // end User.findOne username | |
} // end else existing email | |
}); // end User.findOne email | |
}; // end main func. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment