【发布时间】:2019-03-02 14:24:40
【问题描述】:
尝试使用 Mongoose 对用户进行身份验证时,我在控制台中收到以下警告:
(node:20114) UnhandledPromiseRejectionWarning: undefined
(node:20114) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:20114) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
尝试跟踪堆栈不会产生任何结果,我得到的只是undefined。 Stackoverflow 上也存在类似的问题,但不适用于我的情况。知道这会导致什么吗?
我的路由控制器正在 Mongoose 模型中调用 findByCredentials 函数:
控制器
static login(req, res) {
User.findByCredentials(req.body.email, req.body.password)
.then(user => {
return user.generateAuthToken().then(token => {
res.header("x-auth", token).json(user);
});
})
.catch(error => {
res.status(400).json({ message: "Invalid credentials." });
});
}
型号
userSchema.statics.findByCredentials = function(email, password) {
return this.findOne({ email }).then(user => {
if (!user) {
Promise.reject();
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
res ? resolve(user) : reject();
});
});
});
};
【问题讨论】:
-
你能发布你的
generateAuthToken()方法吗? -
Promise.reject();你没有遗漏退货声明吗?根据该回调中的逻辑,这似乎是您想要的。
标签: javascript node.js mongoose promise