2

I'm using fetch to call Google TimeZone. But I'm getting an error when trying to pass the lat/lng and timestamp in as body paramters.

Error: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body

Here is my code. Does Google allow it to be called this way?

const data = new FormData();
data.append('location', this.latitude.value + ',' + this.longitude.value);
data.append('timestamp', Math.floor(Date.now() / 1000).toString());
data.append('key', 'my google API key')
const timeZoneResult = await fetch('https://maps.googleapis.com/maps/api/timezone/json', {
  method: 'GET',
  headers: {},
  body: data,
});
const timeZone = await timeZoneResult.json();

This way, all in the url string, works fine!

https://maps.googleapis.com/maps/api/timezone/json?location=39.6034810%2C-119.6822510&timestamp=1331161200&key=myKeyHere

chuckd
  • 13,460
  • 29
  • 152
  • 331
  • 1
    a GET request cannot have a body, as the error clearly indicates. A GET is a pure URL-based operation. – Pointy Sep 17 '21 at 22:56
  • is there a way to construct this in parts so I can keep the lat/lng, timestamp and key seperate? Do I just concatenate the string in parts? Is that the only way? – chuckd Sep 17 '21 at 22:59

1 Answers1

9

The error says where the problem is. Method GET cannot have a body. Place the data as a query string.

https://maps.googleapis.com/maps/api/timezone/json?location=...&timestamp=...
  • 8
    It's worth noting that the http specification does not prohibit GET requests from having a body - it is perfectly legal to do so. However, as MDN points out: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET: 'Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined. It is better to just avoid sending payloads in GET requests.' – Midiman Nov 05 '22 at 13:07