I'm trying to build authentication using nodejs with jwt and I successfully finish the register process to register new users to mongo database but I have problem with the login and this is the login code:
// Login
router.post('/log', (req, res) => {
User.findOne({ email: req.body.email }, { password: req.body.pass })
.exec()
.then(function(user) {
bcrypt.compare(req.body.pass, user.pass, (err, result) => {
if (err) {
return res.status(401).send('error');
}
if (result) {
const token = jwt.sign({
email: user.email,
_id: user._id
},
'secret',
{
expiresIn: '1h'
});
return res.status(200).json({
success: 'jwt',
token: token
});
}
return res.status(401).send('error happen');
});
})
.catch(err => {
res.status(401).send(err);
});
});
when I type in postman /log and in the body type this structured:
{
"email": "[email protected]",
"password": "12345",
}
I get this message as response in postman:
error happen
I can't understand what's the error with code while the register worked well ?