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

React无法向MySQL数据库POST数据问题求助

React POST数据到MySQL失败排查

问题概述

使用React向MySQL数据库提交POST数据时失败,已确认接口端点配置,但仍无法正常提交。提交的数据包含p1_question、p1_question_order、type、toggle(固定值"0")、category(数组类型)。

前端代码

publicRequest.jsx

const BASE_URL = "http://localhost:4000/api/"

export const publicRequest = axios.create({
    baseURL: BASE_URL
})

AddQuestion.jsx

const [answerData, setAnswerData] = useState({
 p1_question: "",
 p1_question_order: "",
 type: questionType,
 toggle: "0",
 category: []
})

const handleSubmitQuestion = async (e) => {
e.preventDefault();

try {
  await publicRequest.post('student_q_1', answerData);
  console.log("Success");
} catch (error) {
  console.log(error.message);
  }
}

后端代码

index.js

app.use('/api/student_q_1', studentQuestion1)

app.listen(4000, () =>{
console.log(`Website is running at port http://localhost:${4000}`)
})

router.js

router.post('/', async (req, res) => {
const { p1_question, p1_question_order, type, toggle, category } = req.body;
const query = "INSERT INTO 1_question_student (part_1_question, part_1_question_order, 
type, toggle, category) VALUES (?, ?, ?, ?, ?)";

try {
  const [rows, field] = await connection.execute(query, [
    p1_question,
    p1_question_order,
    type,
    toggle,
    category
  ]);
  res.status(200).json(rows);
} catch (error) {
  res.status(404).json(error);
}
})

可能的失败原因及排查方案

  • 跨域未配置:前端与后端端口不同(通常React默认3000,后端4000),需在后端添加CORS中间件。安装cors包后,在index.js中添加:

    const cors = require('cors');
    app.use(cors());
    
  • 请求体未解析:后端未配置JSON解析中间件,导致req.body为空。在index.js中添加:

    app.use(express.json());
    
  • 数据库字段类型不匹配:category是数组类型,若MySQL字段为JSON类型,需将数组转为JSON字符串后插入:

    JSON.stringify(category)
    

    若字段为VARCHAR,直接插入数组会导致类型错误,需调整字段类型或转换数据格式。

  • SQL表名/字段名语法问题:表名1_question_student以数字开头,MySQL中需用反引号包裹,否则会触发语法错误:

    INSERT INTO `1_question_student` (part_1_question, part_1_question_order, type, toggle, category) VALUES (?, ?, ?, ?, ?)
    
  • 错误信息不足:前端仅打印error.message,无法获取后端具体错误。修改catch块打印详细错误:

    catch (error) {
      console.log(error.response?.data || error.message);
    }
    
  • 数据库字段约束问题:检查1_question_student表中是否有必填字段未赋值,或字段长度限制导致插入失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 07:22:49