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.
>Solution :
You can not use body with GET request. If you want to pass params with GET request then the official way to work with query parameters is just to add them onto the URL. This is an example:
var url = new URL("http://www.localhost:3000/get-data"),
params = {
a: 1,
story: document.getElementsByTagName("input")[0].value,
}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)