【问题标题】:Object not defined when using await使用 await 时未定义对象
【发布时间】:2018-03-05 06:45:14
【问题描述】:

我目前正在尝试向我的节点 API 添加一些身份验证。

现在我正在使用 PassportJS(对这个很新,对我的无能感到抱歉)。

我正在尝试添加本地策略,并在登录时检查用户密码是否合法:

// Local Strategy
passport.use(
  new LocalStrategy(async (username, password, done) => {
    try {
      // Find user by username
      const user = await User.findOne({ username })

      // No user found
      if (!user) {
        return done(null, false)
      }
      console.log('user', user) // Getting output

      // Check if password correct
      const isMatch = await user.isValidPassword(password)

      // Handle if password is not correct
      if (!isMatch) {
        return done(null, false)
      }

      // Return user
      done(null, user)
    } catch (err) {
      done(err, false)
    }
  })
)

我注意到在const isMatch = await user.isValidPassword(password) 上使用await 时,邮递员说:Error: ReferenceError: user is not defined。当我删除await 时,它工作正常,但我可以输入错误的密码,但我仍然可以登录。当我 console.log 时,我可以看到我的 user 对象。

{
    "username": "martinnord3",
    "password": "this_is_the_wrong_password"
}

这是isValidPassword 函数:

UserSchema.methods.isValidPassword = async function(newPassword) {
  try {
    return await bcrypt.compare(newPassword, user.password)
  } catch (err) {
    throw new Error(err)
  }
}

我想我缺少一些明显的东西,但我无法解决这个问题。

感谢您抽出宝贵时间阅读本文!

【问题讨论】:

  • user.isValidPassword(password) 返回什么?无需等待即可尝试。
  • @Firanolfind 你好!退货是什么意思? :O

标签: javascript node.js jwt passport.js


【解决方案1】:

嗯,这有点尴尬,但我想我有责任回答我自己的愚蠢问题...我的函数 isValidPassword 有这个:...user.password 我没有指定 user 在那个函数中是什么.. 它期望this

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 1970-01-01
    • 2021-10-05
    • 2017-07-13
    • 2012-03-16
    • 2021-12-14
    • 2012-04-23
    • 1970-01-01
    • 2017-06-09
    相关资源
    最近更新 更多