Node.js未处理的承诺拒绝



我正在尝试使用 node.js 使用passport进行登录,但是当不在数据库中的用户名尝试登录时,我遇到了问题。我收到以下错误(node:9708) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): TypeError: deferred.resolve is not a 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('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);
});
}));

承诺可以解决或拒绝。您必须为这两种情况编程。在代码末尾添加一个 .catch,如下所示:

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

相关内容

  • 没有找到相关文章

最新更新