Swagger TypeError: 未能在“ Window”上执行“获取”: 带 GET/HEAD 方法的请求不能具有 body

我已经将斯威格添加到我的 Spring Boot 2应用程序中:

这是我的斯威格配置:

@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
}
}

这是 Maven 的依赖:

<!-- 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>

例如,当我尝试调用 http://localhost:8080/api/actuator/auditevents时,它失败了,并出现以下错误:

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

enter image description here

我做错了什么,如何弥补?

216995 次浏览

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

Don't pass method type in Get method.

let res = await fetch("http://localhost:8080/employee_async",{
method: "POST",
body:JSON.stringify(data),
mode:"cors",
headers: {"Content-type":"application/json;charset=utf-8"}})

This is used for post only, If we don't assign any method type node automatically considered as Get method

Maybe the problem is with the mapping of the method, make sure to use @RequestMapping(value = "/<your path>" , method = RequestMethod.POST) and put the data as body with @RequestBody

I had same problem with my .net core 2.0 solution and GET method that takes element id as header key or search for it by parameters in body. That is not the best way to implement but it's kind of special case.

As mentioned in this discussion. The HTTP spec does not forbid using body on a GET, but swagger is not implementing it like this. Even if there are APIs that work fine with body in GET Requests.

What more, the swagger frontend adds this body object into request even if it is null/undefined/empty object. It is -d "body_content_here" parameter. So in my case when i only search by id and body is empty, it still sends empty object (-d "{}") and throws mentioned error.

Possible solutions:

  • Start using postman app for this request - It will work fine. Tested.

  • Consider moving more advanced GET request (like search with criteria) to the independent POST Method

  • Use swagger generated CURL request request without -d parameter

I also got the same error on the Swagger UI. My problem was I have mistakenly marked the Api Method as GET and send data in the request body. Once I change the annotation @GET to @POST issue got resolved.

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.

Looking at swagger exception/error message , looks like you are calling Get method with a set of input body. As per documentation of GET method doesn't accept any body. You need to change the GET method to POST method. It should work.

To avoid this error be sure to annotate parameters in your controller with @RequestParam, like

@GetMapping("/get")
public Response getData(@RequestParam String param)

Because you used GET http method with body. If you want to have Json body, etc you need to use POST http method, For example in your controller class, top of your method:

    @PostMapping(value = "/save")
public ResponseEntity<HttpStatus> savePerson(@RequestBody Person person)
{...}

Use GET without body.

Pass Paremeters with [FromQuery] in Methods InPut

I was having this issue when trying to use Swagger UI on a Ruby On Rails app. I fixed it by changing the information container on the curl command. This is a example line:

parameter name: :body, in: :body, schema: {'$ref' => '#/definitions/ActivitiesFilter'}, required: true

into

parameter name: :attribute_name1, in: :query, required: true
parameter name: :attribute_name2, in: :query, required: true
parameter name: :attribute_name3, in: :query, required: true

note that you have to add as many lines as attributes are defined on your schema inside swagger_helper

This errors happens with wrong argument type. Just change "[FromBody]" to "[FromQuery]".

I faced similar issue; now, it's resolved. You cannot pass parameter to HTTPGET thru Body. To pass parameter to HTTPGet, there are 2 ways either use [FromRoute] or [FromQuery].

If u use [FromRoute], then

[HttpGet("{param1}/{param2}")]
public Person Get([FromRoute]string param1, string param2)
{
}

For PersonController, from client side your url should be: http://localhost:000/api/person/value1/value2

If u want to use [FromQuery]

[HttpGet]
public Person Get([FromQuery]string param1, string param2)
{
}

from client side your url should be: http://localhost:000/api/person?param1=value1&param2=value2