gpt4 book ai didi

javascript - 使用await时 undefined object

转载 作者:行者123 更新时间:2023-12-03 03:24:42 25 4
gpt4 key购买 nike

我目前正在尝试向我的 Node 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)
}
})
)

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

{
"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)
}
}

我想我明显遗漏了一些东西,但我无法解决这个问题。

感谢您花时间阅读本文!

最佳答案

嗯,这有点尴尬,但我想我有责任回答我自己的愚蠢问题...我的函数 isValidPassword 具有以下内容:...user.password 并且我没有指定该函数中的 user 是什么。它需要 this

关于javascript - 使用await时 undefined object ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385864/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com