【问题标题】:Error: Failed to execute 'fetch' on 'Window': Request with GET/HEAD method cannot have body [duplicate]错误:无法在“窗口”上执行“获取”:使用 GET/HEAD 方法的请求不能有正文 [重复]
【发布时间】:2021-11-12 17:37:42
【问题描述】:

我正在使用 fetch 调用 Google TimeZone。但是在尝试将 lat/lng 和时间戳作为正文参数传递时出现错误。

错误:无法在“窗口”上执行“获取”:使用 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();

这样,所有在 url 字符串中,都可以正常工作!

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

【问题讨论】:

  • GET 请求不能有正文,因为错误清楚地表明了这一点。 GET 是纯基于 URL 的操作。
  • 有没有办法分段构造它,这样我就可以保持 lat/lng、时间戳和密钥分开?我只是将字符串部分连接起来吗?这是唯一的方法吗?

标签: javascript google-maps-api-3 fetch google-maps-timezone


【解决方案1】:

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

https://maps.googleapis.com/maps/api/timezone/json?location=...&timestamp=...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-07-22
    • 2022-01-01
    • 2021-11-26
    • 1970-01-01
    • 2017-01-05
    • 2021-04-26
    • 2020-06-28
    相关资源
    最近更新 更多