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

React前端FormData无法传递数据至MySQL数据库问题咨询

React FormData上传MySQL失败排查与解决

问题背景

用React前端通过FormData上传数据到MySQL,Postman测试后端完全正常,但前端提交后数据无法传到后端。数据库仅包含assigned_to和message两个字段,前端状态及switch逻辑自查无问题,怀疑Axios请求存在问题。


代码片段

React前端组件

import axios from 'axios'
import React, { useState } from 'react'

function NotificationSecond() {
    let server ="http://localhost:3456";
    let address = `${server}/user/notification`

  const [Data, setData] = useState({
    assigned_to:"",
    message:""
  })
  const [response, setresponce] = useState();
  
    let submitter = (e)=>{
        e.preventDefault();
        let forForm = new FormData();
        forForm.append('assigned_to',Data.assigned_to)
        forForm.append('message',Data.message)


        axios({
            method:"post",
            url:address,
            data:forForm,
            headers: {"Content-Type": "multipart/form-data" },
        }).then((data)=>{
            setresponce(data.data)
        }).catch((err)=>{
            console.log(err)
        })
    }

    let inputHandler = (e)=>{
        switch (e.target.value) {
            case "assigned_to":setData((pre)=>{return {...pre,assigned_to:e.target.value}})
                
                break;
            case "message":setData((pre)=>{return {...pre,message:e.target.value}})
                
                break;
        
            default:
                break;
        }
    }

    if(response){
        return <div>
            <h1>this is response</h1>
        </div>
    }else{
     return (
     <div>
        <form action="" onSubmit={submitter} >

        <select name="assigned_to" id="" onChange={inputHandler}>
            <option value="one">one</option>
            <option value="two">two</option>
        </select>
        <input type="text" name='message' onChange={inputHandler} />
        <button>submit</button>
        </form>
     </div>
  )
}
}
export default NotificationSecond

后端控制器

import Econnection  from "../server.js";
let notification =(req,res)=>{
    const {assigned_to,message}=req.body
    let value = [assigned_to,message];
    let notificationAdder = `INSERT INTO notification(assigned_to,message) VALUES (?)`;

    Econnection.query(notificationAdder,[value],(err)=>{
         if(err){
            console.log(err)
            res.send('uploading notifications was not successful')
         }else{
            res.send({
                forThanking : `Uploaded successfully,Thank you!`,
                forHomePageReturn: `Click Here To Go Back To Home Page`
            })
         }
    })
}

export default notification;

后端路由

import express from 'express';
import notification from '../Controaller/noticationControler.js';

let notificationRoute = express.Router();

notificationRoute.post('/notification',notification)

export default notificationRoute

核心问题与修复方案

1. 前端输入处理逻辑完全错误

你的inputHandler用e.target.value做switch判断,但实际应该根据表单元素的name属性来匹配状态字段。比如下拉框的name="assigned_to",输入框的name="message",而它们的value是用户选择/输入的内容,根本不可能等于assigned_to或message,导致状态一直没更新。

修复后的inputHandler:

let inputHandler = (e) => {
    const { name, value } = e.target;
    setData(prev => ({ ...prev, [name]: value }));
};

直接解构name和value,用计算属性更新对应状态,无需switch,简洁且不易出错。

2. Axios手动设置Content-Type导致解析失败

手动指定"Content-Type": "multipart/form-data"会丢失自动生成的boundary分隔符,后端无法正确解析FormData。必须去掉这行配置,让Axios自动处理请求头。

修复后的Axios请求:

axios({
    method:"post",
    url:address,
    data:forForm,
    // 移除手动设置的headers
}).then((data)=>{
    setresponce(data.data)
}).catch((err)=>{
    console.log(err)
})

3. 后端需确保配置FormData解析中间件

即使Postman测试正常,也要确认后端是否用了multer解析multipart/form-data。如果没配置,安装并添加到路由:

npm install multer

路由中添加multer中间件:

import multer from 'multer';
const upload = multer(); // 内存存储,仅解析文本字段

notificationRoute.post('/notification', upload.none(), notification);

upload.none()表示只处理文本字段,符合当前无文件上传的场景。


验证步骤

  1. 修复后在submitter里打印状态和FormData,确认数据正确:
console.log('状态数据:', Data);
console.log('FormData:', [...forForm.entries()]);
  1. 打开浏览器Network面板,查看POST请求的Form Data,确认参数已发送。
  2. 后端打印req.body,确认接收到数据:
console.log('接收到的参数:', req.body);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 00:01:28