【问题标题】:CORS error when using await import() with Google API将 await import() 与 Google API 一起使用时出现 CORS 错误
【发布时间】:2020-06-07 05:43:18
【问题描述】:

为什么我会收到 CORS 错误:

Access to script at 'https://maps.googleapis.com/maps/api/js' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

当我尝试在 JavaScript 中动态导入 Google Maps API 时:

  await import('https://maps.googleapis.com/maps/api/js')

但当我在我的 HTML 中执行此操作时不会:

  <script defer src="https://maps.googleapis.com/maps/api/js"></script>

任何想法都会非常感激。

注意:如果我导入其他 URL 库我没有问题,例如:hammer.js cdn

async function init_map() {
  await import('https://maps.googleapis.com/maps/api/js')
}

init_map()

【问题讨论】:

  • 你得到的错误是什么意思?也许谷歌没有设置 CORS 权限来允许它,而其他的却这样做
  • 非常感谢@geocodezip 的回答:),我已经用 CORS 错误更新了帖子:已被 CORS 政策阻止...
  • 但如果谷歌不允许它为什么我能够在 HTML 中做到这一点?
  • 这基本上是我昨天给你解释的。有些端点允许跨域请求,有些则不允许。谷歌没有,至少 Maps API 没有。以下是更多信息:stackoverflow.com/questions/50097327/…
  • 浏览器不检查 CORS 策略以加载脚本标签,而是检查动态加载。

标签: javascript google-maps-api-3 import async-await


【解决方案1】:

我找到了解决办法。但我不确定这是否适用于任何地方。

至少它可以在当前的 Chrome、Firefox 和 Edge 浏览器上运行。

var url = "https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places&key=" + gkey;
$(document.head).append($('<script>', { src: url }));

【讨论】:

  • 非常感谢 Philipp 的解决方案,但我想像使用其他端点一样使用动态导入:)
  • 您可以通过这种方式动态定义 url。这样您就无需担心 CORS 权限。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-10-11
  • 2020-09-07
  • 2023-03-27
  • 2016-10-29
  • 2020-10-09
  • 2021-07-26
  • 1970-01-01
相关资源
最近更新 更多