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

React向NodeJS发起POST请求时请求体参数丢失问题排查

问题:React POST请求体字段无法传递到Node.js后端,MongoDB存入空值

我通过React前端向Node.js后端发送POST请求,试图将新对象存入MongoDB集合。目前能确认对象可以被创建,但所有字段值都是空的。Node.js后端代码单独测试时接口正常,只有通过React前端调用时不符合预期。

React前端代码

const handleSubmit = async (event) => {
    event.preventDefault();

    const requestOptions = {
      method: 'POST',
      mode: 'cors',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        name:nome,
        cnpj:cnpj,
        email:email,
        number:telefone,
        seguradora:[seguradora],
        index:765756
      })
  };
    try{
      const response = await fetch('http://localhost:3001/corretoras',requestOptions)
      const data = await response.json()
      console.log(data)
      console.log(requestOptions.body)
    }
    catch(error){
      console.log('error trying to post',error)
    }
  };

Node.js后端代码

router.post('/',async(req,res)=>{       

    const lastIndex = await Corretora.find().sort({index:-1}).limit(1).index

    const corretora = new Corretora({        
        name:req.body.name,
        cnpj: req.body.cnpj,
        email:req.body.email,
        number:req.body.number,
        seguradora:req.body.seguradora,
        index: lastIndex
    })

    try{
        const novaCorretora = await corretora.save()
        res.redirect('corretoras/'+novaCorretora.id)

    }
    catch{
        renderNewPage(res,corretora,true)
    }
})

React控制台日志

React控制台日志

问题排查与解决方案

1. 后端未配置JSON解析中间件(核心原因)

如果后端没有配置express.json(),则无法解析React发送的JSON格式请求体,导致req.body为空对象。在Express应用的入口文件中添加:

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

// 必须添加这行,解析JSON请求体
app.use(express.json());

2. 修复后端lastIndex获取逻辑

原代码中Corretora.find().sort({index:-1}).limit(1)返回的是数组,直接访问.index会得到undefined,导致index字段为空。修改为:

const lastCorretora = await Corretora.find().sort({index:-1}).limit(1);
const lastIndex = lastCorretora.length > 0 ? lastCorretora[0].index : 0; // 根据业务设置默认值

3. 验证前端变量是否有值

在JSON.stringify前打印前端变量,确认nome、cnpj、email、telefone、seguradora已正确获取表单值:

console.log('前端变量值:', nome, cnpj, email, telefone, seguradora);

如果变量为空,检查表单的value绑定是否正确,比如value={nome} onChange={(e) => setNome(e.target.value)}这类逻辑是否到位。

4. 确认CORS配置完整性

确保后端CORS允许携带Content-Type等必要请求头,可使用cors包简化配置:

const cors = require('cors');
app.use(cors()); // 允许所有跨域请求,生产环境可配置具体origin

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:45:39