【问题标题】:Mongoose Password Compare猫鼬密码比较
【发布时间】:2022-02-01 11:47:00
【问题描述】:

我有一个 node.js 登录表单,它应该验证存在的用户名。然后应该将它与我生成的散列密码进行比较。我能够正确地将新用户注册到 mongodb 数据库。我也能够找到一个()用户。但我无法比较密码。

app.post('/login-users', async (req, res) =>{
   const user = User.findOne({name: req.body.name}, function(err, user){
       console.log('User Found')
   })
  
   try{
    if(await bcrypt.compare(req.body.password, user.password)){
      res.redirect('/')
    } else{
        console.log('Not Allowed')
    }
 } catch {
     res.status(500).send()
 }

})

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    您需要将 try catch 移至回调,因为 user 是一个未解决的承诺

    app.post('/login-users', async (req, res) =>{
       const user = User.findOne({name: req.body.name},async function(err, user){
           console.log('User Found')
            try{
               if(await bcrypt.compare(req.body.password, user.password)){
                res.redirect('/')
               } else{
                console.log('Not Allowed')
               }
           } catch {
             res.status(500).send()
            }
       })
    })
    

    或等待承诺解决

    app.post('/login-users', async (req, res) =>{
       const user = await User.findOne({name: req.body.name})
       try{
        if(await bcrypt.compare(req.body.password, user.password)){
          res.redirect('/')
        } else{
            console.log('Not Allowed')
        }
       } catch {
         res.status(500).send()
     }
    
    })
    

    【讨论】:

      猜你喜欢
      • 2021-08-08
      • 2016-10-01
      • 2020-04-25
      • 2021-04-08
      • 2013-01-13
      • 2018-06-15
      • 2021-06-05
      • 2017-03-08
      相关资源
      最近更新 更多