Reputation: 25770
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.
What am I doing wrong and how to fix it ?
Upvotes: 115
Views: 358837
Reputation: 1
Cannot use body and headers with GET method, Solution 1 - Instead of GET method you can make the method as POST or PUT to send body and headers.
Solution 2 - If you want to send data with GET method you can send it as queryParams
const userDetails = { name: "john", email: "[email protected]", password: "1234", }
const queryParams = new URLSearchParams(userDetails).toString();
You can send queryParams in api url as
await fetch(`http://localhost:8001/user?${queryParams}`, {
method: "GET",
});
and receive it as req.query in backend
Upvotes: 0
Reputation: 1
If you're seeing the error TypeError: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body, it suggests that there might be an issue in the way the controller is handling the request. Specifically, this error occurs when a body is being sent with a GET request, which isn't allowed.
To resolve this issue, check the controller code to ensure the following:
In Spring Boot, the controller method for handling GET requests should receive parameters via:
1.Query parameters (which are passed in the URL).
@GetMapping(
path = "/findById",
params = "id"
)
public CustomerDTO getCustomerById( @RequestParam(value = "id") int CustomerId) {
return customerService.getCustomerById(CustomerId);
}
2.Path variables (part of the URL path).
@DeleteMapping(path = "/delete/{id}")
public String deleteCustomer( @PathVariable(value = "id") int CustomerId) {
return customerService.deleteCustomer(CustomerId);
}
Upvotes: 0
Reputation: 41
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¶m2=value2
Upvotes: 3
Reputation: 339
This errors happens with wrong argument type. Just change "[FromBody]" to "[FromQuery]".
Upvotes: 0
Reputation: 24443
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
Upvotes: 58
Reputation: 1
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
Upvotes: 0
Reputation: 1
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.
Upvotes: 0
Reputation: 947
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.
Upvotes: 68
Reputation: 1325
To avoid this error be sure to annotate parameters in your controller with @RequestParam, like
@GetMapping("/get")
public Response getData(@RequestParam String param)
Upvotes: 5
Reputation: 1209
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.
Upvotes: 3
Reputation: 394
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.
Upvotes: 0
Reputation: 180
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
Upvotes: 11
Reputation: 339
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
Upvotes: 0
Reputation: 51
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
Upvotes: 5