I am sending (rather rying to) send a GET request to my server using the native JavaScript fetch API with an HTML client. On postman I can do this, no problems, what is wrong?
Here is the error:
Unhandled Promise Rejection: TypeError: Request has method 'GET' and cannot have a body
Again, I need to make a GET request, not a post request... Postman does allow this.
Here is the code:
fetch('http://www.localhost:3000/get-data', {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
a: 1,
story: document.getElementsByTagName("input")[0].value,
})
});
PD: I using Safari, bur Chrome, although marking a different looking error that conveys the same message, still does not work.
The HTTP specification makes no mention of a body in a GET request. The server should operate on the URI alone.
The problem here is that Postman is allowing something that is not allowed by the spec. the browser has it right.
If you want to send a body, use a POST method.
For example:
const response = await fetch(url, {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
Code courtesy of MDN