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

Spring Boot/React项目Axios POST请求报400错误求解决方案

Spring Boot/React 应用POST请求400 Bad Request问题排查

问题概述

GET请求可正常获取数据,但POST提交时触发Axios的ERR_BAD_REQUEST错误,状态码400。错误详情如下:

AxiosError {message: 'Request failed with status code 400', name: 'AxiosError', code: 'ERR_BAD_REQUEST', config: {…}, request: XMLHttpRequest, …} code :  "ERR_BAD_REQUEST" config :  {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …} message :  "Request failed with status code 400" name :  "AxiosError" request :  XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} response :  {data: {…}, status: 400, statusText: '', headers: AxiosHeaders, config: {…}, …} stack :  "AxiosError: Request failed with status code 400\n    at settle (http://localhost:3000/static/js/bundle.js:42446:12)\n    at XMLHttpRequest.onloadend (http://localhost:3000/static/js/bundle.js:41141:66)" [[Prototype]] :  Error

相关React组件代码:

import { useState,useEffect } from "react";
import axios from 'axios';

export function Dessert(props) {

    let [price,setPrice]=useState(0);
    let [name,setName]=useState("");
    let [description,setDescription]=useState("");
    let [isEdit,setIsEdit]=useState(props.edit);

    let defaultDate=async()=>{

        if(props.id){
           let dessert;

            let path='http://localhost:8080/dessert/'+props.id;
            await axios.get(path)
                 .then(res => {
                   dessert=res.data;
               }).catch(
               function (error) {
               
              });
console.log(dessert);
            setPrice(dessert.price);
            setName(dessert.name);
            setDescription(dessert.description);
            
        }
    }

    let edit=()=>{
        setIsEdit(!isEdit);
    }
    useEffect(()=>{defaultDate();},[])
    
    let handleSubmit=async(e)=>{
       

        e.preventDefault();
        
             axios({
                method: 'post',
                url: 'http://localhost:8080/dessert',
                data: {
                    name:name,
                    description:description,
                    price:price
                }
              }); 
             
    }
    if(isEdit){
        return(
            <div>
                <form onSubmit={(e)=>handleSubmit(e)}>
                    <div>
                        <label htmlFor="name">Name:</label>
                        <input type="text" onChange={(e)=>{setName(e.currentTarget.value)}} id="name" value={name}/>
                    </div>
                    <div>
                        <label htmlFor="desc">Description:</label>
                        <input type="text" onChange={(e)=>{setDescription(e.currentTarget.value)}} id="desc" value={description} />
                    </div>
                    <div>
                        <label htmlFor="price">Price:</label>
                        <input type="number" onChange={(e)=>{setPrice(e.currentTarget.value)}} id="price" value={price} />
                    </div>
                    <input type="submit" value="Submit"/>
                </form>
                <button onClick={edit}>Read</button>
            </div>
        );
    }
    else if(isEdit&&props.customer){
        <div>
            <div>Name:{name}</div>
            <div>Description:{description}</div>
            <div>Price:{price}</div>
        </div>
    }
    else{
        return(
            <div>
                <div>Name:{name}</div>
                <div>Description:{description}</div>
                <div>Price:{price}</div>
                <button onClick={edit}>Edit</button>
            </div>
        );
    }

}

排查与解决步骤

1. 查看后端详细错误日志

400错误通常是请求参数不符合后端校验规则,直接查看Spring Boot控制台日志,里面会明确指出错误原因:比如字段类型不匹配、必填字段缺失、请求格式错误等,这是最直接的排查方式。

2. 修复请求数据类型不匹配问题

从React代码看,price通过number类型输入框获取,但setPrice(e.currentTarget.value)会把值转为字符串(input的value默认是字符串类型),如果后端实体类的price是Integer或Double类型,会触发类型转换失败导致400错误。

修改price的状态更新逻辑,转为数字类型:

<input type="number" onChange={(e)=>{setPrice(Number(e.currentTarget.value))}} id="price" value={price} />

3. 确保请求格式与后端接收规则一致

Axios默认会把data序列化为JSON,但需确认后端接口是否正确配置接收JSON:

  • 后端Controller方法需添加@RequestBody注解(接收JSON格式参数时)
  • 可在Axios请求中显式指定请求头,避免格式歧义:
axios({
    method: 'post',
    url: 'http://localhost:8080/dessert',
    headers: {
        'Content-Type': 'application/json'
    },
    data: {
        name:name,
        description:description,
        price:price
    }
})
.catch(err => {
    // 打印后端返回的详细错误信息
    console.error("请求错误详情:", err.response.data);
});

4. 验证后端接口映射正确性

确认Spring Boot的Controller接口是@PostMapping("/dessert"),路径与请求中的URL完全一致,避免拼写错误。

5. 检查跨域配置(可选)

虽然GET请求正常,但POST可能因请求头或内容类型触发跨域问题,可确认Spring Boot的CORS配置是否包含POST方法:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .allowCredentials(true);
    }
}

6. 打印完整请求响应信息

在Axios的catch块中打印err.response.data,后端通常会返回具体的错误提示,比如哪个字段校验失败,帮助快速定位问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 08:12:52