【问题标题】:"TypeError: Cannot read property 'status' of undefined" node.js“TypeError:无法读取未定义的属性‘状态’”node.js
【发布时间】:2020-06-17 13:27:26
【问题描述】:

我正在尝试使用 nodejs express.js sequelize 创建一个返回令牌的函数 我得到了这个错误 “TypeError:无法读取未定义的属性‘状态’”

exports.login = (data)=>{
   return user.findOne({
        where : {userName: data.userName}
    }).then(userFound => {
        if (userFound){

            bcrypt.compare(data.password,userFound.password,(errBcrypt,resBcrypt)=>{
                if(resBcrypt) {
                    return {
                        status : 201,
                        token : jwt.sign({id: user.id},secretCode,{expiresIn:'1h'})
                    };
                }else {
                    return {
                        status : 403,
                        errBcrypt : 'password invalid!'
                    };
                }
            })

        }else{
            return {
                status : 403,
                error : 'user not exist!'
            };
        }

    })
    .catch((err) =>{
        return {
            status : 403,
            error : err
        };
    });

}

【问题讨论】:

  • 我在这里看不到任何试图访问 status 属性的东西。错误发生在哪一行?
  • 错误是从哪里来的,你能调试一下吗,因为你提供的代码sn-p应该不会导致问题

标签: javascript node.js express authentication logging


【解决方案1】:

是一个控制器功能还是它在哪里使用也可以尝试返回一个承诺

    exports.login = (data)=>{
   return new Promise((resolve,reject)=>{
   user.findOne({
        where : {userName: data.userName}
    }).then(userFound => {
        if (userFound){

            bcrypt.compare(data.password,userFound.password,(errBcrypt,resBcrypt)=>{
                if(resBcrypt) {
                    return resolve({
                        status : 201,
                        token : jwt.sign({id: user.id},secretCode,{expiresIn:'1h'})
                    })
                }else {
                     return resolve({
                        status : 403,
                        errBcrypt : 'password invalid!'
                    })
                }
            })

        }else{
             return resolve({
                status : 403,
                error : 'user not exist!'
            })
        }

    })
    .catch((err) =>{
         return reject({
            status : 403,
            error : err
        })
    });


   }) 
}

【讨论】:

    猜你喜欢
    • 2019-07-25
    • 2021-11-18
    • 2020-05-15
    • 2020-01-17
    • 2019-10-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多