简体   繁体   中英

Node.js Unhandled promise rejection

I'm trying to make a login with node.js using passport but I'm having a problem when a username that's not in the DB tries to login. I get the following error (node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a function .

Login Function:

exports.login = function(username, password) {
    var deferred = Q.defer;

    MongoClient.connect(mongodbUrl, function(err, db) {
        var collection = db.collection('users');

        collection.findOne({'username' : username}).then(function(result) {
            if (result === null) {
                console.log('User not found:', username);
                deferred.resolve(false);
            } else {
                var hash = result.password;
                console.log('User found:', username);

                if (bcrypt.compareSync(password, hash)) {
                    deferred.resolve(result);
                } else {
                    console.log('Authentication for ' + username + 'failed');
                    deferred.resolve(false);
                }
            }

            db.close();
        });
    }).catch(err => console.log(err));

    return deferred.promise;
};

Passport.use Function:

passport.use('local-signin', new LocalStrategy({passReqToCallback : true}, function(req, username, password, done) {
    funct.login(username, password).then(function(user) {
        if (user) {
            console.log(user.username + 'logged in');
            req.session.success = 'Welcome, ' + user.username + '!';
            done(null, user);
        }

        if (!user) {
            console.log('Failed login attempt');
            req.session.error = 'Your Password or Username is incorrect! Please try again.';
            done(null, user);
        }
    }).fail(function(err) {
        console.log(err.body);
    });
}));

Promises can be resolved or rejected. You have to program for both cases. Add a .catch to the end of your code like so:

collection.findOne({'username' : username}).then().catch(err => console.log(err))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM