【问题标题】:Node.JS variable outside function函数外的 Node.JS 变量
【发布时间】:2015-09-27 04:10:23
【问题描述】:

我在 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");


      })

    }
})

任何人都知道如何解决此问题

谢谢!

【问题讨论】:

  • 找不到这样的user,但“未找到”的测试没有成功。 user 将是 null 或文档 Object。在任何一种情况下,user == '' 都是错误的。 null 仅是 == 对自身或 undefined 并且与字符串比较的对象将首先转换为字符串,从而产生 -- "[object Object]" == "" // false
  • node.js 代码中的prompt() 是什么?
  • 对不起,我不明白,我该如何纠正这个问题?
  • 您可能需要考虑对密码进行哈希处理。
  • 密码已经在数据库中进行了哈希处理,我还没有对用户输入的输入进行哈希处理以与数据库密码进行比较。当我 console.log 收到用户的响应时,>{ _id: 560734a53e04afd4029ab020, username: 'archlinuxusa', password: '9cb1e3525d22f14efd', server: 'ftb', admin: true, __v: 0 }

标签: javascript node.js mongodb if-statement


【解决方案1】:

错误消息Cannot read property 'password' of null 表示usernull。但是代码正在检查空字符串。代替或另外检查null。例如,而不是...:

} else if (user == '') {

...做一些类似这样的事情:

} else if (! user) {

如果user 为空字符串或null 或任何falsy value! user 将为真。

【讨论】:

  • 好吧,问题不在于用户名范围。它带有此代码的密码部分,如果我能以某种方式从第一部分从用户那里获取变量数组,那么当使用提示功能向用户询问他的密码时,它可以成功验证响应与 mongodb 中的内容.这是我的整个代码jsfiddle.net/L3taw280
  • 错误信息表明usernull 并且当您尝试检查user.password 时程序正在崩溃,因为您正在尝试读取nullpassword 属性这是你做不到的。错误是您认为您正在验证 user 已成功检索,但实际上没有。
【解决方案2】:

引发错误的行不一定有任何问题:

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

【讨论】:

  • 使用此方法时,它会破坏整个脚本,当我调试它时,服务器能够找到用户输入的用户名,但由于某种原因,即使脚本能够找到我的数据库中的用户将我发送到“未找到此用户”,当它用于将我发送到下一个密码提示时
  • @ChristopherKemp 请注意,您的查询中可能有错字,属性名称中包含空格和冒号作为字符 -- 'Username: '
  • 在评估查询中的用户名问题并在表中输入已知用户名时。你叫什么名字?>archlinuxusa scs >找不到这个用户
  • 我的代码和我的陈述存在一些问题,这些问题与我评估您上面所说的内容的方式以及我使用 findOne 函数的方式有关。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-12
  • 2013-03-27
  • 2021-01-24
  • 2019-09-15
相关资源
最近更新 更多