首页 > 解决方案 > 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)。在我做了一些调试之后,问题是

  1. 当我调试await bcrypt.compare(password, user.password)时,我发现它看起来像是在未散列的“密码”与存储的(散列的)密码“user.password”之间进行比较
  2. 如果我跳过bcrypt.compare,它会返回相关的文档数据(即使提供的密码不匹配)
  3. 显示错误消息
(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.
  1. 我在 nodeV14 上运行

介意任何人知道如何解决它,提前谢谢

标签: node.jsmongodbjwtbcrypt

解决方案


推荐阅读