向 Google Places API 发送详细信息请求 -(CORS 错误) [英] Sending a details request to Google Places API - (CORS error)
问题描述
我正在尝试使用来自 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.
- 如何制作在我的本地主机上获取 CORS 请求?
希望这会有所帮助!
这篇关于向 Google Places API 发送详细信息请求 -(CORS 错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!