基于Axios以列表为参数调用Spring Boot接口:GET请求为何失效?
GET请求传递列表参数到Spring Boot接口失效的原因及解决办法
问题详情
尝试通过GET方法向Spring Boot接口传递列表参数获取数据,但仅POST方法能正常工作,相关代码及报错如下:
控制器方法
@RequestMapping("/test6") public ResponseEntity<List<String>> test6(@RequestBody List<String> shoppingList){ System.out.println(shoppingList.size()); System.out.println("From frontend: " + shoppingList.toString()); return new ResponseEntity<>(shoppingList, HttpStatus.OK); }
Axios GET请求代码
const shoppingList2 = ["apple, ball"]; axios .get("http://localhost:8081/test7?", shoppingList2) .then(function (response) { console.log(response.data); });
Spring Boot报错信息
2023-01-27T14:40:21.365+01:00 WARN 15488 --- [nio-8081-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.http.converter.HttpMessageNotReadableException: Required request body is missing: public org.springframework.http.ResponseEntity<java.util.List<java.lang.String>> com.maremare.foodhunter.controller.TestController.test7(java.util.List<java.lang.String>)]
正常工作的Axios POST请求
const shoppingList2 = ["apple, ball"]; axios .post("http://localhost:8081/test6?", shoppingList2) .then(function (response) { console.log(response.data); });
失效原因
- @RequestBody不支持GET请求:
@RequestBody注解的作用是读取HTTP请求体中的数据并绑定到方法参数,但HTTP规范中GET请求没有请求体(即便部分客户端允许携带,Spring Boot默认也不会解析GET请求的请求体),因此Spring Boot会抛出"请求体缺失"的错误。 - Axios GET参数传递方式错误:Axios的
get方法第二个参数是请求配置对象,而非请求体数据。直接传入数组无法将参数正确拼接到URL的查询参数中,即便想通过请求体传递GET参数,也不符合HTTP规范且不被Spring支持。
修正方案
要实现GET请求传递列表参数,需调整控制器参数绑定方式和前端请求参数传递方式:
修正后的控制器方法
使用@RequestParam注解绑定URL查询参数,Spring Boot会自动将多个同名查询参数解析为List:
@RequestMapping("/test6") public ResponseEntity<List<String>> test6(@RequestParam List<String> shoppingList) { System.out.println(shoppingList.size()); System.out.println("From frontend: " + shoppingList.toString()); return new ResponseEntity<>(shoppingList, HttpStatus.OK); }
修正后的Axios GET请求
通过params配置项传递列表参数,Axios会自动将其拼接为?shoppingList=apple&shoppingList=ball格式的查询参数:
const shoppingList2 = ["apple", "ball"]; axios.get("http://localhost:8081/test6", { params: { shoppingList: shoppingList2 } }) .then(function (response) { console.log(response.data); });
内容的提问来源于stack exchange,提问作者Maremare
相关产品推荐
相关产品推荐

