当尝试使用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();
});
});
});
};
答案 0 :(得分:1)
错误undefined
来自您的Promise.reject()
,您没有向其传递任何错误消息,因此实际上是抛出未定义的错误消息。
由于您不是通过findByCredentials
方法返回它,因此没有被登录时捕获。
解决方案:
userSchema.statics.findByCredentials = function(email, password) {
return this.findOne({ email }).then(user => {
if (!user) {
return Promise.reject('User not available');
}
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, res) => {
res ? resolve(user) : reject();
});
});
});
};