skip to Main Content
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


  1. 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.

    var myHeaders = new Headers();
    
    var queryParams = {
      "userId": 1
    };
    
    var params = new URLSearchParams(queryParams);
    
    var requestOptions = {
      method: 'GET',
      headers: myHeaders,
      redirect: 'follow'
    };
    
    fetch("https://mcqapi.onrender.com/api/dashboard?" + params, requestOptions)
      .then(response => response.text())
      .then(result => console.log(result))
      .catch(error => console.log('error', error));
    Login or Signup to reply.
  2. error TypeError: Failed to execute ‘fetch’ on ‘Window’: Request with GET/HEAD method cannot have body

    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:

    • Consult the documentation for the API you are using to see how to correctly make the request (assuming it allows you to make it in a compliant way)
    • Change the API you are accessing to pass the data in the query string (and make it compliant)
    • Build a server-side proxy using a language + HTTP request library combination that supports GET requests with bodies.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search