2017-10-01 17 views
0

ユーザーを自分のアプリケーションにログインさせるカスタムミドルウェアを作成しようとしています。しかし、私は戻って、次のエラーメッセージを取得していますログインしているユーザーを確認してください

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待つshouldn私は、以下の機能を使用しています。このため get an object back. However, I am gettingは未定義です。

私が間違っていることは何ですか?

あなたの返信を歓迎します!

答えて

0

これが見つかりました。https://github.com/mysqljs/mysql/issues/910#issuecomment-55536265です。

は、私はここで起こっていると思うことは、あなたがそのエラーCannot read property '0' of undefinedを得ている理由ですので、あなたのクエリは空の配列を返すと.first()方法が、その場合には定義されていない[0]項目で何かをやっているということです。

あなたはこのような何かやってあなたのコードを向上させることができます

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) 
    } 
} 
関連する問題