问题
I am trying to build an authentication panel for the MEAN stack using PassportJS. I have the following code for registering new users with email(instead of the default username) and password:
router.post("/register", function (req, res) {
var newUser = new User({
username: req.body.email
});
User.register(newUser, req.body.password, function (err, user) {
if (err) {
return res.render('account/signup');
}
passport.authenticate("local")(req, res, function () {
res.redirect("/account/profile");
});
});
});
However, when running the server, I am presented with a screen on which it is written Bad Request. It can be assumed that the new user account is being successfully created as I am able to log in that account.
I believe that the error originates somewhere around here:
passport.authenticate("local")(req, res, function () {
res.redirect("/account/profile");
});
回答1:
passport.authenticate
is a middleware, which means that you have to call it with 3 parameters (req, res, next)
:
...
passport.authenticate("local", function(err, user, info) {
if (err) return next(err);
if (!user) return res.redirect('/login');
req.logIn(user, function(err) {
if (err) return next(err);
return res.redirect("/account/profile");
});
})(req, res, next);
...
Or use it inside post method:
router.post("/register", function (req, res, next) {
var newUser = new User({
username: req.body.email
});
User.register(newUser, req.body.password, function (err, user) {
if (err) {
return res.render('account/signup');
}
// go to the next middleware
next();
});
}, passport.authenticate('local', {
successRedirect: '/account/profile',
failureRedirect: '/login'
}));
来源:https://stackoverflow.com/questions/48096378/bad-request-when-registering-with-passport