React js向Spring启动请求发送json失败,状态代码为400



我试图将在前端react js部分创建的状态发送到后端spring引导部分,并在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;


}
}

首先,您可以从控制器中删除@Controller注释,因为您已经有了@RestController注释,使其成为rest控制器。第二,如果您想让请求主体或json发送到端点,请使用POST请求。如果你问我为什么不将请求体与GET请求一起使用,简短的版本是因为HTTP规范,请阅读:HTTP GET与请求体

http状态代码400基本上是因为Bad请求。问题出在控制器端点上。您将从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
}

更改代码如下:

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

最新更新