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

React宠物添加表单提交触发SQL查询错误,请求排查原因

解决AddPet组件提交FormData到后端的查询错误

1. 核心错误:后端多余的bcrypt加密逻辑

你的后端代码里毫无必要地调用了bcrypt.hash(req.body.password, 10, ...),但前端提交的FormData里根本没有password字段,这会导致req.body.password为undefined,触发bcrypt报错,直接返回"Query Error"。添加宠物信息不需要密码加密逻辑,完全可以删除这部分代码。

修复后的后端代码:

router.post("/add-pet", upload.single("image"), (req, res) => {
    // 先检查图片是否上传成功
    if (!req.file) {
        return res.json({ Status: false, Error: "请选择宠物图片" });
    }

    const sql = `INSERT INTO pets (pet_owner_id, pet_nickname, pet_nb_chip, pet_type, pet_breed, pet_gender, pet_birth_date, pet_height, pet_weight, pet_vaccinated, image, pet_vaccination_id, vet_id, category_id) 
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;
    const values = [
        req.body.pet_owner_id,
        req.body.pet_nickname,
        req.body.pet_nb_chip,
        req.body.pet_type,
        req.body.pet_breed,
        req.body.pet_gender,
        req.body.pet_birth_date,
        req.body.pet_height,
        req.body.pet_weight,
        req.body.pet_vaccinated === "true" ? 1 : 0, // 转换为数据库支持的布尔类型(如tinyint)
        req.file.filename,
        req.body.pet_vaccination_id,
        req.body.vet_id,
        req.body.category_id,
    ];
    con.query(sql, values, (err, result) => {
        if (err) return res.json({ Status: false, Error: err.message });
        return res.json({ Status: true });
    });
});

2. SQL插入语句的参数格式错误

原SQL使用VALUES (?),但传入的values是一维数组,这种写法要么把values包裹成二维数组[values],要么直接把SQL写成VALUES (?, ?, ?, ...)对应每个字段。上面的修复采用了第二种方式,更直观不易出错。

3. React组件的状态冗余优化

你的pet状态初始化了pet_vet_id,但实际表单绑定和提交的是vet_id,这个冗余字段可以删除,避免混淆:

const [pet, setPet] = useState({
    pet_owner_id: "",
    pet_nickname: "",
    pet_nb_chip: "",
    pet_type: "",
    pet_breed: "",
    pet_gender: "",
    pet_birth_date: null,
    pet_height: "",
    pet_weight: "",
    pet_vaccinated: false,
    image: "",
    pet_vaccination_id: "",
    vet_id: "", // 保留这个,删除pet_vet_id
    category_id: "",
});

4. 复选框值的类型转换

前端复选框的pet_vaccinated是布尔值,FormData会自动转为字符串"true"/"false",后端需要转换为数据库支持的布尔类型(如MySQL的tinyint 1/0),修复代码中已经处理了这个转换。

5. 调试建议

  • 前端提交前打印FormData内容,确认字段完整:
    const handleSubmit = (e) => {
      e.preventDefault();
      const formData = new FormData();
      // ... 字段追加逻辑
      console.log("FormData内容:", [...formData.entries()]);
      // ... axios提交逻辑
    };
    
  • 后端打印接收的参数,确认数据正确:
    router.post("/add-pet", upload.single("image"), (req, res) => {
      console.log("接收的表单数据:", req.body);
      console.log("接收的文件:", req.file);
      // ... 后续逻辑
    });
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 07:49:52