【问题标题】:Running into cors issue trying to use Google API [duplicate]尝试使用 Google API 时遇到 cors 问题 [重复]
【发布时间】:2018-07-19 17:47:33
【问题描述】:

我现在正在构建一个 React 应用程序并尝试使用 Google Places API 来填充我的应用程序中缺少的地点数据(公司名称、描述、照片等)

我尝试过使用 fetch() 以及 axios 库,但没有成功。继续看到这个错误

Failed to load https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJN1t_tDeuEmsRUsoyG83frY4&key=XXXXXXX: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

提前感谢您的帮助。

【问题讨论】:

  • 可能和这个差不多,看看:stackoverflow.com/questions/39329874/…
  • 你能把你的代码复制粘贴到这里吗?
  • stackoverflow.com/questions/44336773/…stackoverflow.com/questions/43443836/…。 Places API 并非有意不启用 CORS。唯一支持使用 Places API 的方式是 Google 文档显示它正在使用的方式——这不涉及使用 XHR 或 Fetch API 或 JavaScript 库中的 Ajax 方法对其进行调用。
  • @sideshowbarker 我担心这可能是唯一的解决方案。我不需要显示地图对象,所以我试图避免在加载地图而不是仅仅为了使用 api 的地方显示它。 :( 认为这个库可能会帮助我,但它仍然给出了 CORS 错误:github.com/mcabs3/google-places-web
  • Places API 网络服务应该被称为服务器端,在客户端你必须使用 Maps JavaScript API 的places 库。

标签: javascript reactjs google-maps-api-3 cors


【解决方案1】:

使用这个库有很多令人困惑的信息,尤其是在 React 项目中。这是我终于能够开始工作的解决方案。

index.html

<Head>
  <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXX&libraries=places"
async defer></script>
</Head>
<Body>
  <div id="map"></div>
</Body>

反应组件

componentDidMount() {

const googleMap = new window.google.maps.Map(document.getElementById('map'),{center: { lat: -33.867, lng: 151.206 },zoom: 15});

基本上,我必须发现的技巧是使用 window 对象来访问我的 google 变量。现在您有了 googleMap,您可以轻松地连接到其他 google api 服务。希望这对其他人有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-24
    • 2020-01-05
    • 2021-09-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多