我正在尝试编写一个自定义中间件来将用户登录到我的应用程序中。 为此,我使用以下功能:
async function login(username, password) {
try {
const pwdHash = await bcrypt.hash(password, saltRounds)
const res = await knex("users").where({
username: username,
password: pwdHash
}).first()
console.log("res: " + res) //here I am getting the error
if (res.password == pwdHash) {
return true
} else {
return false
}
} catch (e) {
console.log(e)
}
}
但是,我收到以下错误消息:
TypeError: Cannot read property '0' of undefined
at Object.login (C:\Users\user\project\service\user.js:56:34)
at <anonymous>
我知道我无法立即访问res
对象,但不应该t
等待get an object back. However, I am getting
未定义`。
有什么建议我做错了吗?
感谢您的回复!
答案 0 :(得分:0)
我发现了这个,https://github.com/mysqljs/mysql/issues/910#issuecomment-55536265。
我认为这里发生的是你的查询返回一个空数组,而.first()
方法正在对[0]
项做一些事情,在这种情况下是未定义的,所以&#39; s为什么会收到该错误Cannot read property '0' of undefined
。
您可以通过以下方式改进代码:
async function login(username, password) {
try {
const pwdHash = await bcrypt.hash(password, saltRounds)
const res = await knex("users").where({
username: username,
password: pwdHash
});
// res should be an empty array here if there is no match
// Just check if the query gives you some result
// so, if the array has some item inside then it means
// that you found a valid user with that `username` and `password`
if (res.length > 0) {
return true
} else {
return false
}
} catch (e) {
console.log(e)
}
}