You need to enable JavaScript to run this app. ReactJS表单如何提交至NodeJS 解决后端req.body返回undefined问题
优惠活动
大模型
产品
解决方案
定价
更多

ReactJS表单如何提交至NodeJS 解决后端req.body返回undefined问题

req.body 返回 undefined 问题修复方案

核心原因

两个配置/逻辑问题共同导致了异常:

  • Express 端未配置对应请求体解析中间件,框架不会自动解析 JSON 格式的请求内容,直接读取 req.body 自然返回 undefined
  • React 端表单存在原生提交逻辑冲突,触发请求时会同时发起自定义 fetch 请求、浏览器原生表单POST请求,两种请求格式不一致,容易导致后端接收到的请求和预期不符

修复步骤

1. Express 端注册 JSON 解析中间件

Express 4.16+ 版本已内置请求体解析能力,需要在所有路由定义/挂载代码之前注册对应中间件,位置不能靠后,否则中间件对路由不生效:

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

// 必须放在所有 app.use(router) 这类路由挂载代码之前
app.use(express.json());

// 原有路由逻辑保持不变
router.post('/signup', (req, res) => {
    console.log(req.body)
    // 补充响应逻辑,避免请求挂起
    res.json({ status: 'success', data: req.body })
});

如果你的后端还需要接收表单格式的请求,可以额外注册 app.use(express.urlencoded({ extended: true })) 中间件做兼容

2. 调整 React 端表单提交逻辑

现有代码的 form 标签自带原生提交属性,内部的 button 默认是 submit 类型,点击时会触发页面跳转、双请求并发的问题,需要做如下调整:

  • 删除 form 标签上冗余的 action、method 属性,所有请求逻辑交由 fetch 处理
  • 给表单的提交动作绑定 preventDefault,阻止浏览器原生跳转行为
  • 统一用表单的 onSubmit 事件触发请求,替代按钮的独立 onClick 逻辑
    修改后的关键代码:
class SignUp extends React.Component {
    constructor() {
        super();
        this.state = {
            username: '',
            email: '',
            password: ''
        }
    }

    onChange = (e) => {
        this.setState({ [e.target.name]: e.target.value });
    }

    newUser = (e) => {
        // 阻止表单默认提交跳转
        e.preventDefault();
        fetch('http://localhost:4000/signup', {
            method: "POST",
            headers: {
                'Content-type': 'application/json'
            },
            body: JSON.stringify(this.state)
        })
        .then((response) => response.json())
        .then((result) => {
            console.log(result)
        })
    }

    render() {
        return (
        <div>
            {/* 移除原生的action、method属性,绑定onSubmit事件 */}
            <form onSubmit={this.newUser}>
                <input onChange={this.onChange} type="text" name="username" placeholder="Username" />
                <input onChange={this.onChange} type="text" name="email" placeholder="Email" />
                <input onChange={this.onChange} type="password" name="password" placeholder="Password"/>
                <button type="submit">Sign Up</button>
            </form>
        </div>
        )
    }
}

额外注意事项

如果前端和后端运行在不同端口,属于跨域请求范围,需要在 Express 端配置跨域允许规则,否则 fetch 请求会被浏览器安全策略拦截,无法到达后端路由。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 13:24:09