[英]Check logged in user
I am trying to write a custom middleware to log a user into my application. 我正在尝试编写自定义中间件以将用户登录到我的应用程序。 For this I am using the below function: 为此,我使用以下功能:
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)
}
}
However, I am getting the following error message back: 但是,我收到以下错误消息:
TypeError: Cannot read property '0' of undefined
at Object.login (C:\Users\user\project\service\user.js:56:34)
at <anonymous>
I know that I cannot access the res
object immediately, but shouldn t
await get an object back. However, I am getting
我知道,我不能访问该res
立即反对,但不应该t
的await get an object back. However, I am getting
get an object back. However, I am getting
undefined` back. get an object back. However, I am getting
回来get an object back. However, I am getting
undefined`。
Any suggestions what I am doing wrong? 有什么建议我做错了吗?
Appreciate your replies! 感谢您的答复!
I found this, https://github.com/mysqljs/mysql/issues/910#issuecomment-55536265 . 我发现了这个https://github.com/mysqljs/mysql/issues/910#issuecomment-55536265
what I think is happening here is that your query is returning an empty array and the .first()
method is doing something with the [0]
item which is undefined in that case, so that's why you are getting that error Cannot read property '0' of undefined
. 我想这里发生的是您的查询返回一个空数组,并且.first()
方法正在使用[0]
项(在这种情况下未定义.first()
做某事,因此这就是您收到该错误的原因Cannot read property '0' of undefined
。
You can improve your code doing something like this: 您可以通过以下方式改进代码:
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)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.