向 Google Places API 发送详细信息请求 -(CORS 错误) [英] Sending a details request to Google Places API - (CORS error)

查看:27
本文介绍了向 Google Places API 发送详细信息请求 -(CORS 错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用来自 Google Places API 的照片来增加我在这个项目中为公共艺术作品收集的照片.它说这里您可以发送详细信息请求以获取包含十张照片的数组.最终,我将打开响应以获取 Google 对每张照片的 照片参考 并提出请求为数组中的每张照片并显示它.

I'm trying to augment the collection of photos I have for public artworks in this project I'm working on with photos from the Google Places API. It says 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 for each photo and make requests for each photo in the array and display it.

很遗憾,当我发送详细信息请求时,这个计划就中断了.这是我得到的确切错误:

Unfortunately, this plan breaks when I send my details request. This is the exact error I'm getting:

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 Maps API 和其他几个)都是按原样编写的,所以我有点困惑为什么我会收到错误.以下是相关代码:

I'm running this from my localhost and I'm pretty sure that matters. All of my other API calls (Google Maps API and a couple others) are written exactly as this is, so I'm a little confused why I'm getting the error. Here is the relevant code:

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()
    })
}

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

Let me know if you need any other information, I'd be happy to provide it. Thanks!

推荐答案

你需要使用一个 服务器端代理 来防止这个错误.当您直接访问 url 时它会起作用,因为这样做时您没有来源.

You need to use a server side proxy to prevent this error. It works when you access the url directly because you have no origin when you do that.

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

检查这个相关的 SO 问题:

Check this related SO question:

您可以修改您的 API 服务器以启用 CORS,或者按照 关于 webpack-dev-server 的说明与现有服务器结合"下的页面,将资产服务与 webpack-dev-server 和您自己的 API 服务器结合起来.

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.

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆