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

React通过axios.post提交表单到Express后端失败问题排查

问题根因

提交失效是多个前后端代码问题共同导致的,核心问题如下:

  • 后端未配置JSON请求体解析中间件,也没有编写POST /api的处理接口,根本无法接收、处理新增请求
  • 后端存储的user1数组写在GET接口内部,每次请求都会返回固定初始值,新增数据无法持久保存
  • 后端初始返回数据存在语法错误:第二条数据的Name字段缺失闭合引号,接口直接返回会报错
  • 前端存在多处未定义变量:userList、userData、clearForm、大写开头的User,代码运行直接抛错
  • 前端提交成功后没有刷新本地存储的列表数据,即使后端新增成功也看不到最新结果
修正方案

1. 后端 Server.js 修正

按以下逻辑调整代码:

  • 新增express.json()中间件,自动解析axios发送的JSON格式请求体
  • 将user1数组提升为全局变量存储,避免每次GET请求重置数据
  • 新增POST /api接口,实现参数校验、id自增、数据插入逻辑
  • 修复原有初始数据的语法错误,补全缺失字段

修正后完整代码:

const express = require('express');
const app = express();
const cors=require("cors");

const corsOptions ={
    origin:'*',
    credentials:true,
    optionSuccessStatus:200,
}

app.use(cors(corsOptions))
// 解析JSON请求体
app.use(express.json());

// 全局存储测试数据,生产环境请替换为数据库存储
let userStore = {
    user1: [
        {
            id: 1,
            Name: "Isabella",
            Introduction: "测试用户1"
        },
        {
            id:2,
            Name: "Catalina",
            Introduction: "测试用户2"
        }
    ]
}

app.get("/api",(req,res)=> {
    res.json(userStore)
});

// 新增条目处理接口
app.post("/api",(req,res)=> {
    const newItem = req.body;
    // 基础参数校验
    if (!newItem.Name || !newItem.Introduction) {
        return res.status(400).json({code: 400, msg: "Name和Introduction不能为空"});
    }
    // 生成自增ID
    const nextId = userStore.user1.length ? userStore.user1.at(-1).id + 1 : 1;
    // 插入新条目
    userStore.user1.push({
        id: nextId,
        Name: newItem.Name,
        Introduction: newItem.Introduction
    })
    res.json({code: 200, msg: "新增成功", data: userStore})
});

app.listen(5000,()=>{
    console.log("Server started on port 5000");
})

2. 前端 Form.js 修正

按以下逻辑调整代码:

  • 补全缺失的clearForm表单清空方法
  • 替换所有未定义变量,基于已拉取的backendData计算新条目ID
  • 修复渲染部分的变量拼写、引用错误
  • 提交成功后重新拉取后端最新数据,刷新列表展示,同时清空表单
  • 新增请求异常捕获,方便排查问题

修正后完整代码:

import "./form.css";
import React, {useEffect,useState} from "react";
import {addBeauty,deleteB} from "./beauty";
import Modal from "./Modal";
import axios from 'axios';


export default function CreateForm() {

    const [Name, setName] = useState("");
    const [Intro, setIntro] = useState("");
    const [isOpen, setIsOpen] = useState();

    const [backendData, setBackendData] = useState({});

    // 拉取后端数据通用方法
    const fetchData = async () => {
        const res = await fetch("http://localhost:5000/api");
        const data = await res.json();
        setBackendData(data);
    }

    useEffect(()=>{
        fetchData()
    },[]);

    // 补全清空表单方法
    const clearForm = (e) => {
        e.preventDefault();
        setName("");
        setIntro("");
    }

    const handleSubmit = async (event)=>{
        event.preventDefault();
        // 基于现有后端数据计算新ID,兼容空列表场景
        const nextId = backendData.user1?.length ? backendData.user1.at(-1).id +1 : 1;
        try {
            await axios.post("http://localhost:5000/api",{
                id: nextId, 
                Name:Name, 
                Introduction:Intro
            })
            // 提交成功后刷新列表、清空表单
            await fetchData();
            setName("");
            setIntro("");
        } catch (err) {
            console.error("提交失败:", err);
        }
    }

    return (
        <div className="container">
            
            <form className="add" onSubmit={handleSubmit} >
                <h2>User</h2>
                <label htmlFor= "name">Name</label>
                <input type="text"    value={Name}
                       onChange={(event) => {setName(event.target.value);}}/>
                <label htmlFor= "Intro">Introduction</label>
                <input type="text"   value={Intro}
                       onChange={(event) => {setIntro(event.target.value);}}/>

                <p></p>
                <p></p>

                <div className = "press">
                    <button  id = "1" type="submit">
                        Add Beauty
                    </button>
                    <button  id = "2"
                             onClick={clearForm}
                    >
                        Clear Form
                    </button>
                </div>
            </form>

            <br></br>
            <br></br>
            <br></br>

            <div className="display">
                {/* 修复未定义的userData变量 */}
                {(typeof backendData.user1 === 'undefined')?(
                    <h1>Loading</h1>):(
                    backendData.user1.map((user,i)=>{
                        return (
                            <div key={user.id}>
                                <h1> {user.Name}</h1>
                  
                                <button onClick={()=>{
                                    setIsOpen(user.id);
                                }}>View in popup</button>
                                <Modal open={isOpen === user.id} onClose={()=>setIsOpen(undefined)}>
                                    {/* 修复大写User的拼写错误 */}
                                    <h3> {user.Introduction}</h3>
                                </Modal>

                            </div>
                        );})
                )}

            </div>
        </div>
    );
}
验证方式
  • 先重启后端服务,执行node Server.js,控制台输出Server started on port 5000即为启动成功
  • 重启React前端服务,页面加载完成后在表单输入Name、Introduction内容,点击Add Beauty按钮,即可看到新条目实时出现在下方列表中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 13:09:26