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

React表单数据无法传递至Express后端问题求助

解决React + Express表单提交数据无法获取的问题

问题根源

你的Express代码里,app.use("/", (req,res)=>{...}) 这个中间件会匹配所有HTTP方法的根路径请求,而且它被写在了POST路由前面。当你发送POST请求到/时,这个中间件会先处理请求并返回{"message":"Hello World"},后面的POST路由根本没机会执行,自然拿不到表单数据。

修复步骤

  1. 调整路由顺序:把这个全局根路径中间件移到POST路由之后,或者直接删掉(它只是返回Hello World,对你的表单提交逻辑没用)。
  2. 保留请求体解析中间件:你已经正确添加了express.json()和express.urlencoded(),这俩负责解析JSON和表单格式的请求体,必须保留。

修复后的完整代码

Express端 app.js

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

const app = express()
app.use(cors())
// 解析请求体的中间件,建议给urlencoded加上extended:true,支持复杂对象解析
app.use(express.urlencoded({ extended: true }))
app.use(express.json())

// 先定义POST路由,确保能被匹配到
app.post('/', (req, res) => {
    const { fullname, age } = req.body;
    console.log('收到表单数据:', fullname, age);
    res.send('Form submitted successfully');
});

// 如果需要根路径的GET请求,单独定义GET路由即可
app.get('/', (req, res) => {
    res.json({ message: "Hello World" });
})

app.listen(5000, () => {
    console.log("服务器运行在 http://localhost:5000");
})

React端组件代码

import React from "react";

export default function App(){
  function submitHandler(e){
    e.preventDefault();
    const fullname = e.target.elements.fullname.value;
    const age = e.target.elements.age.value;
    
    fetch('http://localhost:5000/', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ fullname, age })
    })
    .then(response => response.text())
    .then(data => {
        console.log(data); // 现在会输出"Form submitted successfully"
    })
    .catch(err => console.error('请求出错:', err)); // 建议加上错误捕获,方便排查问题
}

  return (
    <div className="App">
      <form onSubmit={submitHandler}>
        <input type="text" name="fullname" placeholder="Name:" />
        <input type="number" name="age" placeholder="age" />
        <input type="submit" value="Submit" />
      </form>
    </div>
  );
}

验证效果

  1. 重启Express服务器和React应用
  2. 填写表单提交后,Express控制台会打印你输入的姓名和年龄,React控制台会输出Form submitted successfully
  3. 之后你就可以在POST路由里添加MongoDB存储逻辑,比如用Mongoose连接数据库并保存数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:15:47