簡體   English   中英

Node.JS變量外函數

[英]Node.JS variable outside function

我在node.js中使用mongodb和mongoose,在函數內部,它驗證用戶名和密碼。 user.password在第一個if語句中起作用,但之后在下面的if else中,用戶實際使用的位置將返回。

              if (password1 == user.password) {
                                   ^
TypeError: Cannot read property 'password' of null

我擁有的代碼是。

User.findOne({ 'Username: ': username1}, function(err, user) {
    if (err){
        console.log("There was an error proccesing the request".red + " : ".red + err);
    } else if (user == '') {
        console.log("This user was not found")

    } else {
      prompt('Password: ', function(password1){
          if (password1 == user.password) {

              console.log("User Login Sucsess")
          } else {

              console.log("Password incorrect")
              proccess.exit();
          }


          console.log("made it");


      })

    }
})

任何人都知道如何解決此問題

謝謝!

錯誤消息Cannot read property 'password' of null表示usernull 但是代碼正在檢查空字符串。 檢查是否為null替代或附加。 例如,代替...:

} else if (user == '') {

...做更多這樣的事情:

} else if (! user) {

! user ! user如果將真正的user是空字符串或null或任何falsy值

引發錯誤的行不一定有任何錯誤:

if (password1 == user.password) {

在確定問題的地方更是如此。 問題的根源在於幾行:

} else if (user == '') {
    console.log("This user was not found")

錯誤消息表明usernull (因為null不能具有.password屬性),這意味着在這種情況下,找不到與查詢匹配的文檔。 但是,條件並沒有解決這個問題,它允許函數繼續執行,並在沒有user嘗試讀取user.password

這是因為null == ''false 在JavaScript中, null值本身==undefined

var user = null;
console.log(user == '');        // false

console.log(null == '');        // false
console.log(null == null);      // true
console.log(null == undefined); // true

調整條件以專門檢查是否為null可以解決此問題:

} else if (user == null) {
    console.log("This user was not found")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM