You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js使用bcrypt哈希加密时登录校验报错问题求助

问题原因与修复方案

核心报错原因

你收到Error: data and hash arguments required报错的直接原因是bcrypt.compareSync的第二个参数为undefined:

  • 注册逻辑中,你把加密后的密码存在了数据库表的password字段
  • 登录校验时你错误读取了user.hash字段,这个字段在你的表结构中不存在,自然拿不到哈希值

其他代码问题

你还混用了bcrypt的同步/异步调用逻辑,同时存在响应重复返回的问题:

  • 所有带Sync后缀的bcrypt方法都是同步方法,不需要加await
  • 登录逻辑中如果用户存在的场景下,你已经调用了response.json()返回结果,最后又统一return response.json(user)会触发「响应头已发送」报错
  • 注册逻辑中bcrypt.genSaltSync不需要加await,生成的哈希本身就是字符串,不需要调用toString('hex')

修复后代码

注册方法修复

async create(request, response){
    const {id, email, password, cpf, name, lastName, cellphone} = request.body;
    // 同步方法不需要加await
    let salt = bcrypt.genSaltSync(10);
    let hash = bcrypt.hashSync(password, salt);

    const newUser = await connection('login').insert({
        id,
        email,
        password: hash, // 哈希值存储在password字段
        cpf,
        name,
        lastName,
        cellphone,
    });
    // bcrypt生成的哈希本身就是字符串 不需要额外转hex
    return response.json({id: newUser[0], token: hash});
},

登录方法修复

async login(request, response){
    const {email, password} = request.body;
    const user = await connection('login').first('*').where({email:email});

    if(user){
        // 第二个参数读取存储密码的password字段,同步方法不需要加await
        const validPass = bcrypt.compareSync(password, user.password);
        if(validPass){
            // 直接return避免后续重复返回响应
            return response.status(200).json('valid Email and pass!');
        }else{
            return response.json('Wrong pass!')
        }
    }else{
        return response.status(400).json({error: 'No user found with this E-mail'});
    }
}

内容的提问来源于stack exchange,提问作者felipi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 01:27:03