MySQL中点击一次数据重复保存两次如何解决?仅存bcrypt加密的单条用户记录
问题修复方案
根因说明
你代码中执行了两次用户写入操作,因此产生两条记录:
- 第一次执行
Users.create(tutorials)时,直接写入了携带明文密码的用户数据,对应你看到的明文记录 - 第二次在create执行成功的回调中,又通过
Users.build().save()写入了携带哈希密码的用户数据,对应第二条加密记录
修复代码
你只需要先完成密码哈希,再执行一次数据库写入即可,修复后的接口逻辑如下:
const bcrypt = require('bcryptjs'); // 确保已提前引入bcrypt依赖 exports.create = async (req, res) => { // 原有参数校验逻辑保留 if (!req.body.age) { return res.status(400).send({ message: "Age can not be empty!" }) } if (!req.body.name) { return res.status(400).send({ message: "Name can not be empty!" }) } if (!req.body.email) { return res.status(400).send({ message: "email can not be empty!" }) } if (!req.body.password) { return res.status(400).send({ message: "Password can not be empty!" }) } try { // 先计算密码哈希 const hash = await bcrypt.hash(req.body.password, 8); // 组装用户数据,直接使用哈希后的密码 const user = { age: req.body.age, name: req.body.name, email: req.body.email, password: hash }; // 仅执行一次写入操作 await Users.create(user); res.status(200).json({ message: 'Created Database with Hashed password' }) } catch (e) { console.log(e); res.status(500).send({ message: e.message || "Some error occurred while creating the User." }) } };
额外优化建议
- 原代码使用的
bcrypt.hashSync是同步方法,会阻塞Node.js事件循环,推荐改用异步的bcrypt.hash配合async/await写法 - 可以给users表的email字段加唯一索引,避免重复注册相同邮箱的用户
- 不要在代码任何位置打印或返回明文密码,避免日志泄露敏感信息
内容的提问来源于stack exchange,提问作者AskAnyWay
相关产品推荐
相关产品推荐

