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

React通过Axios向Node.js后端POST数据时后端无法获取数据

React Axios POST请求后端无法读取数据的解决方法

问题场景

在React项目中使用Axios发起POST请求向Node.js后端传递数据,但后端无法读取到数据,报错如下:

前端提交代码

function Submit() {
    let params={
        firstName:name,
        lastName:lastName,
        email:email,
        passwordKey:pass,
        statut:1
    }

    axios.post(`http://localhost:8080/new_user`,stringify(params))
    .then((response)=>(console.log(response)))
}

Node.js后端路由代码

app.post('/new_user',(req,res)=>{
    const recived=req.body.params
    console.log(recived)
    /*const query = `INSERT INTO user  VALUES()`;
    db.query( query,function (error ,results){
        if(!error ){
            return  res.status(201).json(results)
        }
        else{
                //return   res.status(503).json({"message":"Error in connection"})
                return res.status(500).json(data)
        }
    })*/
})

后端错误信息(中文翻译)

TypeError: 无法读取未定义的属性 'params'
    在 C:\reactjs\Back-end\index.js:65:28
    在 Layer.handle [as handle_request] (C:\reactjs\Back-end\node_modules\express\lib\router\layer.js:95:5)      
    在 next (C:\reactjs\Back-end\node_modules\express\lib\router\route.js:144:13)
    在 Route.dispatch (C:\reactjs\Back-end\node_modules\express\lib\router\route.js:114:3)
    在 Layer.handle [as handle_request] (C:\reactjs\Back-end\node_modules\express\lib\router\layer.js:95:5)      
    在 C:\reactjs\Back-end\node_modules\express\lib\router\index.js:284:15
    在 Function.process_params (C:\reactjs\Back-end\node_modules\express\lib\router\index.js:346:12)
    在 next (C:\reactjs\Back-end\node_modules\express\lib\router\index.js:280:10)
    在 serveStatic (C:\reactjs\Back-end\node_modules\serve-static\index.js:75:16)
    在 Layer.handle [as handle_request] (C:\reactjs\Back-end\node_modules\express\lib\router\layer.js:95:5)      

问题原因

  1. 前端手动调用stringify序列化参数,但未设置正确的Content-Type请求头,导致后端无法解析请求体
  2. 后端错误尝试读取req.body.params,实际传递的数据直接存在req.body对象中
  3. 后端未配置解析JSON请求体的中间件,导致req.body为undefined

修复方案

1. 修正前端代码

Axios会自动处理对象的JSON序列化并设置正确请求头,无需手动调用stringify:

function Submit() {
    let params={
        firstName:name,
        lastName:lastName,
        email:email,
        passwordKey:pass,
        statut:1
    }

    axios.post(`http://localhost:8080/new_user`, params)
    .then(response => console.log(response))
    .catch(error => console.error(error))
}

2. 配置后端中间件

在后端入口文件(如index.js)中添加JSON解析中间件(Express 4.16+自带,无需额外安装):

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

// 解析JSON格式请求体
app.use(express.json());
// 可选:解析表单格式请求体
app.use(express.urlencoded({ extended: true }));

3. 修正后端路由逻辑

直接读取req.body获取传递的数据,而非req.body.params:

app.post('/new_user',(req,res)=>{
    const received = req.body;
    console.log(received);
    
    // 示例数据库操作(按需启用)
    /*const query = `INSERT INTO user (firstName, lastName, email, passwordKey, statut) VALUES (?, ?, ?, ?, ?)`;
    db.query(query, [received.firstName, received.lastName, received.email, received.passwordKey, received.statut], function(error, results) {
        if (!error) {
            return res.status(201).json(results);
        } else {
            return res.status(500).json({ message: "数据库操作失败", error: error.message });
        }
    })*/
})

额外提示

  • 若出现跨域问题,后端需配置CORS,可安装cors包并添加app.use(cors())
  • 检查前端name、lastName等变量是否有有效值,避免传递空数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 00:30:31