Bad Request when registering with passport

非 Y 不嫁゛ 提交于 2021-01-28 10:47:27

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!