Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swagger TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

I have added Swagger to my Spring Boot 2 application:

This is my Swagger config:

@Configuration @EnableSwagger2 public class SwaggerConfig {      @Bean     public Docket api() {         // @formatter:off         return new Docket(DocumentationType.SWAGGER_2)                   .select()                                                   .apis(RequestHandlerSelectors.any())                               .paths(PathSelectors.any())                                           .build();         // @formatter:on     } } 

This is Maven dependency:

<!-- Swagger2 --> <dependency>     <groupId>io.springfox</groupId>     <artifactId>springfox-swagger2</artifactId>     <version>2.8.0</version> </dependency> <dependency>     <groupId>io.springfox</groupId>     <artifactId>springfox-swagger-ui</artifactId>     <version>2.8.0</version> </dependency> 

When I try to invoke for example http://localhost:8080/api/actuator/auditevents it fails with the following error:

TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body. 

enter image description here

What am I doing wrong and how to fix it ?

like image 988
alexanoid Avatar asked Feb 12 '18 14:02

alexanoid


Video Answer


2 Answers

The error message actually says what the problem is. You post data with curl using the -d option while trying to use GET.

If you use the -d option curl will do POST.
If you use -X GET option curl will do GET.

The HTTP GET method is for requesting a representation of the specified resource. Requests using GET should only retrieve data and hence cannot have body.

More info on GET vs POST

like image 81
Boris Avatar answered Sep 20 '22 15:09

Boris


I ran into this issue. Here is how I resolved it:

I had a method like this:

[HttpGet] public IEnumerable<MyObject> Get(MyObject dto) {       ... } 

and I was getting the error. I believe swagger UI is interpreting the Get parameters as FromBody, so it uses the curl -d flag. I added the [FromQuery] decorator and the problem was resolved:

[HttpGet] public IEnumerable<MyObject> Get([FromQuery]MyObject dto) {       ... } 

FYI this also changes the UI experience for that method. instead of supplying json, you will have a form field for each property of the parameter object.

like image 38
ironfist Avatar answered Sep 19 '22 15:09

ironfist