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

React调用SpringBoot POST接口遇Axios 400错误求助

排查React Axios调用SpringBoot POST接口返回400错误的原因

400错误通常是请求格式不正确或参数不符合后端要求导致的,结合你Postman调用正常、React调用失败的情况,按以下方向排查:

1. 检查请求字段是否完全匹配

SpringBoot实体类的字段名是大小写敏感的,对比你Postman的请求体,确认前端signUpData的字段名和后端完全一致:

  • Postman示例字段:userName、userEmail、password、about
  • 在submitForm中打印signUpData,检查是否存在字段名拼写错误(比如把userName写成username)、缺失必填字段的情况。

2. 确认Axios请求头配置

后端接收JSON格式请求时,需要请求头Content-Type: application/json。检查你的myAxios实例是否配置了正确的请求头:

// Constant.js 中的myAxios配置示例
import axios from "axios";

export const myAxios = axios.create({
  baseURL: "你的后端API基础地址",
  headers: {
    "Content-Type": "application/json"
  }
});

如果前端默认发送的是表单编码格式(application/x-www-form-urlencoded),后端未配置对应解析器会直接返回400。

3. 验证数据类型与后端要求一致

检查前端提交的字段数据类型是否和后端实体类匹配:

  • 比如后端password是String类型,前端是否误传了数字;
  • 必填字段是否传了undefined/null,触发后端的非空校验(比如@NotBlank注解)。

4. 查看后端日志定位具体错误

查看SpringBoot应用的控制台日志,通常会输出参数绑定失败、校验不通过的具体信息(比如邮箱格式不符合@Email规则、密码长度不够),这是最直接的排查依据。

5. 确认Axios的请求序列化逻辑

确保Axios将JavaScript对象正确序列化为JSON字符串。如果myAxios修改过默认的transformRequest,可能导致序列化异常,可以手动指定序列化方式:

// 修改UserService.js中的saveUser方法
export const saveUser = (user) => {
  return myAxios.post("/user/register-user", JSON.stringify(user), {
    headers: {
      "Content-Type": "application/json"
    }
  }).then((response) => response.data);
};

附你提供的相关代码

UserService.js

import axios from "axios";
import { myAxios } from "./Constant";

export const saveUser =  (user) => {
    return myAxios.post("/user/register-user",user).then((response) => response.data);
}

SignUp.js

const submitForm = async (event)=>{
  // stopping default behavior of submit
  event.preventDefault()
  
  //console.log('data submitted')
  console.log(signUpData)
  
  // validate form data

  // call server api to submit form data
  saveUser(signUpData)
  .then((resp) => {
    console.log(resp);
    console.log("success log");
  }).catch((error) => {
    console.log(error);
    //console.log("Error log");
  })
}

Postman正常请求体示例

{
"userName":"ram",
"userEmail":"ram@gmail.com",
"password":"pwd5",
"about":"ram is a react developer working in xyz"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:45:45