未处理的拒绝TypeError:无法读取null

时间:2017-08-08 04:30:39

标签: javascript mysql node.js sequelize.js

我正在使用NodeJS,PassportJS,MySQL和Sequalize(ORM for MySQL)。此代码来自我的Passport.JS文件。当用户在我的网站上注册用户名或电子邮件时,我将返回错误。如果在数据库中找不到用户名,电子邮件,则将创建新的创建帐户。

我在网站上注册时遇到的错误是......

Unhandled rejection TypeError: Cannot read property 'username' of null
    at null.<anonymous> (/home/ubuntu/workspace/Authentication.1/config/passport/passport.js:50:16)
    at tryCatcher (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/promise.js:693:18)
    at Async._drainQueue (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:133:16)
    at Async._drainQueues (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:143:10)
    at Immediate.Async.drainQueues [as _onImmediate] (/home/ubuntu/workspace/Authentication.1/node_modules/sequelize/node_modules/bluebird/js/release/async.js:17:14)

我的代码是:

        User.findOne({
            // SELECT * FROM users WHERE username = username || email = ... 
            where: {
                $or: [{username: username}, {email: req.body.email}]
            }
        }).then(function(user){

        // GETTING ERROR HERE. If username is already in database
        if(user.username !== null && user.username == req.body.username) {
          return done(null, false, console.log("USER TAKEN"),{message : 'That username is already taken'} );
        }

        // If email is already in database return err.
        else if(user.email !== null && user.email == req.body.email) {
          return done(null, false, console.log("EMAIL TAKEN"),{message : 'That email is already taken'} );
        }

        else [code for create new account]...

1 个答案:

答案 0 :(得分:2)

您的问题来自if声明中的第一次检查。如果找不到用户,user将为空,语句user.username !== null将导致您收到错误消息。

您应该对整个对象执行空检查,而不是属性。 if(user!== null && user.username == req.body.username){...}