Reputation: 35693
Getting my API data via Postman works fine but when running following code in my js application I get an error: Request with GET/HEAD method cannot have body.
var myHeaders = new Headers();
myHeaders.append("Authorization", "Bearer mybearertoken");
var formdata = new FormData();
formdata.append("Id", "56afb645-6084-4129-6469-08d91f4770af");
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: formdata,
redirect: 'follow'
};
fetch("https://myapi.com/api/Konfigurator/GetProjekt", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
Upvotes: 2
Views: 12809
Reputation: 708
You are adding body
to a http GET request.
change your method to POST and everything will be fine. (if you handle it correctly on server)
Example:
var url = "/api/route";
var formdata = new FormData();
formdata.append("id", "123");
// before - if not defined, the default method value is 'get'
var options = { body: formData };
// after - set method to 'post'
var options = { body: formData, method: "post" };
var response = await fetch(url, options);
var data = await response.json();
Upvotes: 3
Reputation: 17858
As per the specification;
If this’s request method is
GET
orHEAD
, then set body to null.
GET and HEAD requests do not have a body, so all parameters should be in the URL.
As for Postman concern, technically, you can send any HTTP request with a body in it as long as the http web server can read it. Nothing prevents get request of having a body. This is an ongoing discussion regarding limitation of how much query string can URL parameters contain and how people need to supply complex parameters into a GET request.
However, some people just tend to keep it as a best practice
by utilizing other http methods for body and other went along with it.
Upvotes: 7