node.js - bcrypt.compare JWT 与 nodeJS,Mongoose 总是抛出错误
问题描述
当我尝试在 NodeJS 中实现 JWT,Mongoose 作为我的身份验证机制时,我遇到了这个有点傻的问题。
假设我尝试使用此代码(NodeJS)实现登录功能
const post_login = async (req, res, next) => {
const userData = req.body;
try {
const user = await User.login(userData);
res.status(200).json({user: user._id});
} catch (error) {
res.status(400).json({});
}
// res.json(userData)
};
然后我在我的模型数据中附加这个函数
UserSchema.statics.login = async function(userData){
const {email, password} = userData;
const user = await this.findOne({email});
if (user) {
const auth = await bcrypt.compare(password, user.password)
if (auth) {
return user;
}
throw Error('Password do not match');
}
throw Error('Email is not registered');
};
我在 mongoDB 中存储数据时成功实现了 bcrypt.hash。但是,当我尝试这些代码时,它总是抛出一个错误(状态 4000)。在我做了一些调试之后,问题是
- 当我调试
await bcrypt.compare(password, user.password)
时,我发现它看起来像是在未散列的“密码”与存储的(散列的)密码“user.password”之间进行比较 - 如果我跳过
bcrypt.compare
,它会返回相关的文档数据(即使提供的密码不匹配) - 显示错误消息
(node:11784) UnhandledPromiseRejectionWarning: Error: data and hash arguments required
at Object.compare (E:\practice\jwt\node_modules\bcrypt\bcrypt.js:208:17)
at E:\practice\jwt\node_modules\bcrypt\promises.js:29:12
at new Promise (<anonymous>)
at Object.module.exports.promise (E:\practice\jwt\node_modules\bcrypt\promises.js:20:12)
at Object.compare (E:\practice\jwt\node_modules\bcrypt\bcrypt.js:204:25)
at E:\practice\jwt\models\user-model.js:67:20
(Use `node --trace-warnings ...` to show where the warning was created)
(node:11784) 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(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:11784) [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.
- 我在 nodeV14 上运行
介意任何人知道如何解决它,提前谢谢
解决方案
推荐阅读
- sql - 以下查询的 SQL 查询优化
- javascript - 如何在 DevTools JavaScript 调试器中搜索关键字?
- docker - docker-compose 使用带有弹性搜索的卷
- cypress - 赛普拉斯信用卡到期日期在 MMYY 格式中跳过斜线
- java - 压缩pdf文件并下载在java中给出损坏的文件
- python - ModuleNotFoundError 当它实际上在路径中时
- python - GPU 上的 Keras 模型:在自定义损失函数中使用 Pandas
- sql - 将现有记录的副本创建到新行中并更新一些值
- sql - 基于具有不同值的单独列重复一组列的选择
- html - 使用引导程序将 svg/div 居中到中心