-3

how to send a data object using fetch when the used method is GET? i tried body method but, the browser compiler tells me "GET/HEAD" can't have a body

this was my code:

var myHeaders = new Headers();
var raw = JSON.stringify({
  "token": "<secret>"
});

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  body: raw,
  redirect: 'follow'
};

fetch("https://www.quickly-egypt.com/api/v1/client/address/all", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

tried sending data using GET method and it failed

1
  • 1
    "the browser compiler tells me "GET/HEAD" can't have a body" this is correct - by the HTTP standard it cannot. Some tools may not enforce it but it's not something you should rely on. If you want to send a body, don't use a bodyless verb. Or you send the information in a different way outside the body. Commented Nov 1, 2022 at 11:46

1 Answer 1

0

Append a ?token=xyz to the url or do something like

url = "https://.../all?" + new URLSearchParams({
  token: 'xyz',
  // more data
})
fetch(url)

Alternative:

const url = new URL('https://.../all')
url.searchParams.set('token', 'abc')
fetch(url)
Sign up to request clarification or add additional context in comments.

2 Comments

Or maybe it's part of the headers. Hard to guess. Moreover, I don't think we should be guessing. It's really up to the documentation to determine that and OP would be in the best position to have access to it.
I can confirm that it works with url params...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.