我正在尝试将MongoDB / Mongoose集成到https://github.com/cornflourblue/node-jwt-authentication-api中。但是我对users / user.service.js中的authenticate函数有疑问
async function authenticate({ email, password }) {
db.admin.findOne({email: email}, (err, admin) => {
if (!err) {
bcrypt.compare(password, admin.password, function(err, res) {
if (err) console.log(err);
if (res) {
const token = jwt.sign({ sub: admin._id }, config.secret);
const { password, ...userWithoutPassword } = admin;
console.log({...userWithoutPassword, token});
return {
...userWithoutPassword,
token
};
}
});
}else{
console.error(err);
}
})
}
现在的问题是return函数不返回其内容。在users / users.controller.js
function authenticate(req, res, next) {
userService.authenticate(req.body)
/* .then(user => {
console.log(user.token)
user ? res.json(user) : res.status(400).json({ message: 'E-Mail or password is incorrect' })
}) */
.then(ret => {
console.log(ret)
res.status(400).json({status: 400})
})
.catch(err => next(err));
}
第二个文件中的console.log在第一个文件中调用console.log之前为控制台提供了未定义的内容。