Search code examples
javascriptgoogle-maps-api-3fetch-apigoogle-maps-timezone

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


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


Solution

  • 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=...