向 Google 地点 API 发送详细信息请求 -(CORS 错误)

Sending a details request to Google Places API - (CORS error)

我正在尝试增加我在这个项目中的 public 艺术作品的照片集,我正在处理来自 Google 个地点 API 的照片。它为每张照片显示 here that you can send a details request to get an array of ten photos. Eventually I will unpack the response to get Google's photo reference,并对数组中的每张照片发出请求并显示它。

不幸的是,当我发送我的详细信息请求时,这个计划中断了。这是我得到的确切错误:

Fetch API cannot load https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJ5zf5lfXKRIYR8rPafbwaL68&key=MY_API_KEY. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:4040' is therefore not allowed access. 
If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

我是 运行 来自本地主机的,我很确定这很重要。我的所有其他 API 调用(Google 地图 API 和其他几个调用)都是按原样编写的,所以我有点困惑为什么我会收到错误。这是相关代码:

The actual API call:

export function getPhotos(placeID) {
  let obj = {
    method: 'GET'
  };
  return fetch('https://maps.googleapis.com/maps/api/place/details/json?placeid=' + placeID + '&key=MY_API_KEY')
    .then((response) => {
      if (response.status >= 400){
        throw new Error("Error getting photos for placeID: " + placeID)
      }
      return response.json()
    })
}

如果您需要任何其他信息,请告诉我,我们很乐意提供。谢谢!

您需要使用 server side proxy 来防止此错误。当您直接访问 url 时它会起作用,因为当您这样做时您没有来源。

  • JS AJAX 向本地服务器请求 -> 远程服务器,收到请求,发送响应,远程服务器 -> 本地服务器 -> AJAX 向 JS 请求。

检查这个相关的 SO 问题:

  • What to do when an API doesn't allow Access-Control-Allow-Origin
  • webpack dev server CORS issue

You can either modify your API server so that CORS is enabled, or follow the instructions on the webpack-dev-server page under "Combining with an existing server" to combine asset serving with webpack-dev-server and your own API server.

  • How do I make a CORS request with fetch on my localhost?

希望对您有所帮助!

建议使用服务器端代理。虽然这对于访问不支持 CORS 或 JSONP 的 Web API 的一般情况来说是一个很好的解决方案,但它不是针对此特定问题的最佳解决方案。

相反,请使用专为此类用途设计的 Google 的 JavaScript Places Library。该页面顶部的链接提供了其他示例、指南和参考 material。

我提出了一个类似的问题,但已关闭:-

我在使用本地主机的 google api 时遇到了完全相同的问题。经过痛苦的一天尝试各种事情之后,解决方案非常简单。

我添加了 Allow CORS: Access-Control-Allow-Origin chrome 扩展,将 api 列入白名单并打开了 COR。 这是一个非常古老的问题,当时的解决方案可能不可行,但我希望有一天它能对某人有所帮助!