var myHeaders = new Headers();
myHeaders.append("Content-Type", "application/json");
var raw = JSON.stringify({
"userId": 1
});
var requestOptions = {
method: 'GET',
headers: myHeaders,
body: raw,
redirect: 'follow'
};
fetch("https://mcqapi.onrender.com/api/dashboard", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));
I am tying to get data from dashboard which needs a key userId but since in sql procedure the userId is actually referring to different table so I have to use this method but its not working either and giving following problem in the console:
error TypeError: Failed to execute ‘fetch’ on ‘Window’: Request with GET/HEAD method cannot have body.
at API testing.html:30:1
2
Answers
Since the request you are trying to execute is a GET request, it cannot have a body payload. It would help to double-check the API routing or documentation where the API requires you to send the userId.
You are most likely trying to send a GET with query string data. You can convert your data to query string parameters and pass them along to the server that way. This is shown below.
The error message is explicit and correct. You cannot make a GET request from the browser with a body.
The HTTP specification doesn’t outright forbid GET requests from having bodies, but it does state the behaviour is undefined. You shouldn’t try to make GET requests with bodies or write services that expect them.
Either: