-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

Endless
  • 34,080
  • 13
  • 108
  • 131
  • 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. – VLAZ Nov 01 '22 at 11:46

1 Answers1

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)
Endless
  • 34,080
  • 13
  • 108
  • 131
  • 1
    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. – VLAZ Nov 01 '22 at 11:48
  • I can confirm that it works with url params... – Endless Nov 01 '22 at 11:50