注册工作正常;
登录时,我总是收到错误消息:Invalid login credentials
正如你在我的代码中看到的那样,如果bcrypt compare返回false,我应该收到此消息
我无法弄清楚我哪里出错了,
登录ctrl
User.findOne({
email: req.body.email
}, function (err, user) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
if (!user) {
return res.status(401).json({
title: 'Login failed',
error: {
message: 'Invalid login credentials'
}
});
}
if (!bcrypt.compareSync(req.body.password, user.password)) {
return res.status(401).json({
title: 'Login failed',
error: {
message: 'Invalid login credentials'
}
});
}
var token = jwt.sign({
user: user
}, 'secret', {
expiresIn: 7200
});
res.status(200).json({
message: 'Successfully logged in',
token: token,
userId: user._id
});
})
},
注册Ctrl
signup: function (req, res) {
console.log(req.body)
var user = new User({
firstName: req.body.firstName,
lastName: req.body.lastName,
password: bcrypt.hashSync(req.body.password, 10),
email: req.body.email
});
user.save(function(err, result) {
if (err) {
return res.status(500).json({
title: 'An error occurred',
error: err
});
}
res.status(201).json({
message: 'User created',
obj: result
});
});
}