错误:无法在“Window”上执行“fetch”:使用 GET/HEAD 方法的请求不能有正文

use*_*050 3 javascript fetch google-maps-api-3 google-maps-timezone

我正在使用 fetch 来调用Google TimeZone。但是当我尝试将纬度/经度和时间戳作为正文参数传递时,出现错误。

错误:无法在“Window”上执行“fetch”:使用 GET/HEAD 方法的请求不能有正文

这是我的代码。Google 允许这样称呼吗?

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();
Run Code Online (Sandbox Code Playgroud)

这样,所有的内容都在 url 字符串中,工作正常!

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

小智 10

该错误表明问题出在哪里。方法 GET 不能有主体。将数据作为查询字符串放置。

https://maps.googleapis.com/maps/api/timezone/json?location=...&timestamp=...
Run Code Online (Sandbox Code Playgroud)

  • 值得注意的是,http 规范并不禁止 GET 请求拥有主体 - 这样做是完全合法的。然而,正如 MDN 指出的:https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET:'注意:在 GET 请求中发送正文/有效负载可能会导致某些现有实现拒绝请求——虽然规范没有禁止,但语义是未定义的。最好避免在 GET 请求中发送有效负载。 (11认同)