【问题标题】:I trying authenticate a user using passport.js but it gives me a error **the server responded with a status of 400 (Bad Request)**我尝试使用 passport.js 对用户进行身份验证,但它给了我一个错误**服务器响应状态为 400(错误请求)**
【发布时间】:2021-02-04 03:51:13
【问题描述】:

当我注册用户时,它成功保存到数据库中,但是当我对用户进行身份验证时,它给了我 400 (Bad Request) 错误

在此我使用 passport.js、passport-local、passport-local-mongoose 进行身份验证

这是我的代码:

mongoose.connect("mongodb://localhost:27017/logindb", {useNewUrlParser: true});
    
const userSchema = new mongoose.Schema({
    username: String,
    password: String
});
    
userSchema.plugin(passportLocalMongoose);        
    
const User = mongoose.model('User', userSchema);
passport.use(User.createStrategy());

serializeUser 和 deserializeUser 的代码:

passport.serializeUser(User.serializeUser());    
passport.deserializeUser(User.deserializeUser());

这是我注册用户和验证用户的代码:

app.post('/register', function(req, res){
    
        User.register({username: req.body.email}, req.body.password, function(err, user) {
            if (err) {console.log(err); res.redirect('/'); }
            else{
                passport.authenticate('local')(req, res, function(){
                    res.redirect('/home')
                })
                res.redirect('login')
            }
            
        });
    
})

【问题讨论】:

    标签: javascript node.js mongodb mongoose passport.js


    【解决方案1】:

    你弄错了sintex。 试试这个:

    passport.authenticate('local'), function (req, res){
      res.redirect('/home')
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-30
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 2022-06-15
      相关资源
      最近更新 更多