我正在构建一个简单的登录应用程序,并且发生了一件奇怪的事情。我设置的方式是:
我遇到的问题是,如果我从客户端发送错误的密码,findOne回调不会给我记录或错误,这很奇怪,因为应该在回调中检查密码,以及查询密码首先没有提供。 代码如下:
router.post('/', function(req, res, next){
User.findOne({username: req.body.username}, 'username password _id', function(err, user){
if (err) {
return next(err);
}
if(user) {
bcrypt.compare(req.body.password, user.password, function(err, valid) {
if (err) {
return next(err);
}
if(!valid) {
res.send({error: 'wrong password'});
} else {
var token = jwt.encode({id: user._id}, config.secret);
res.send(201, token);
}
})
} else {// this block is executed if the wrong password is sent, but it shouldn't, it should be if the username is wrong, right?
res.send({error: 'wrong username'});
}
})
})
基本上,如果发送了错误的密码,user
为null
并且代码的else块被执行,密码永远不会被比较。
答案 0 :(得分:1)
通常findOne
不会抛出error
,而是在找不到null
时返回match
。
您可以使用like
这个:
User.findOne( {...}, function (err, result) {
if (err) { return next(err) }
if (!result) {
// do stuff here
}
}