【问题标题】:React js sending json to Spring boot Request failed with status code 400React js 向 Spring Boot 发送 json 请求失败,状态码为 400
【发布时间】:2020-11-24 14:41:47
【问题描述】:

我正在尝试将在前端 react js 部分创建的状态发送到后端 spring boot 部分并以 JSON 模式读取我的状态,我使用了 Axios 但我收到此错误:

请求失败,状态码 400

我的前端代码:

onSubmit(e){
    e.preventDefault();
    const FilterRegion={
      //region
     eu:this.state.eu,
      americas:this.state.americas,
      aae:this.state.aae,
      ger:this.state.ger,
      eu2:this.state.eu2,
      latam : this.state.latam,
      empty:this.state.empty,
      allregion:this.state.allregion,
       }
    console.log(FilterRegion)
    axios.get("http://localhost:8080/MenuFiltre/filtreregioncloser",FilterRegion)
  }

后端控制器:

@Controller
@RequestMapping("/MenuFiltre")
@RestController
@CrossOrigin()
public class MenuFiltre {
    @GetMapping("/filtreregioncloser")
    public Iterable<Closerfprfx>gettab1(@RequestBody String jsonStr)
    {
        JSONObject jObject = new JSONObject(jsonStr);
         System.out.println(jsonStr);

        return null;

        
        
    }

}

【问题讨论】:

  • 尝试将 React 排除在等式之外,然后在 Postman 中尝试。检查您的 url 在 React 和 Postman 匹配中是否匹配。我还将提供您的“filteredRegion”对象的外观。我不认为你可以像你一样传递你的对象。可能是错的,但由于您调用的是“get”方法,我原以为您必须使用 eu='a'&=americas='a'&=..... 传递一个字符串,也许它已被处理由 axios 自动执行,但我对此表示怀疑。其他人可能会证实这一点。
  • 不建议使用 Get 和 body。您可以尝试在 react 和 spring-boot 中将 get 更改为 POST。

标签: json reactjs spring-boot axios


【解决方案1】:

首先,您可以从控制器中删除 @Controller 注释,因为您已经拥有 @RestController 注释以使其成为休息控制器。其次,如果您想将请求正文或 json 发送到端点,请使用 POST 请求。如果你问我为什么不使用带有 GET 请求的请求正文,简短的版本是因为 HTTP 规范,请阅读:HTTP GET with request body

http状态码400基本上是因为Bad request。问题在于您的控制器端点。您正在从您的 ui 以 json 格式发送数据。不要从请求正文中将数据作为字符串读取,而是使用像 FilterRegion 这样的 pojo 类:

@PostMapping("/filtreregioncloser")
public Iterable<Closerfprfx>gettab1(@RequestBody FilterRegion filterRegion)
{
     //No need for Jsonobject while using POJO springboot will convert it for you from json to POJO
     System.out.println(filterRegion);
     return null;      
}

使用 json 中的字段创建 POJO 类 FilterRegion,例如:

class FilterRegion {
 String eu;
 String americas;
 //Add other fields and the constructor,getters and setters
}

【讨论】:

    【解决方案2】:

    如下更改您的代码:

    axios.get("http://localhost:8080/MenuFiltre/filtreregioncloser",JSON.stringify(FilterRegion))
    

    【讨论】:

      猜你喜欢
      • 2022-06-21
      • 2019-09-29
      • 1970-01-01
      • 2017-06-02
      • 2021-01-12
      • 2020-10-21
      • 2021-11-09
      • 2021-04-07
      • 2020-04-25
      相关资源
      最近更新 更多