CORS 和 Angular $http GET 到 Google Places API [英] CORS and Angular $http GET to Google Places API
问题描述
Angular 新手,尝试使用 Google Maps/Places API 设置一个非常简单的应用程序.
New to angular, trying to setup a very simple application using the Google Maps / Places API.
我可以通过以下方式成功使用地理定位服务:
I can successfully use the geolocation service with:
.controller('MainCtrl', [
'$scope',
'$http',
function($scope, $http){
$scope.userLocation = [];
$scope.currentLocation = function() {
$http({
method: 'GET',
url: 'https://www.googleapis.com/geolocation/v1/geolocate?key=xxx'
}).then(function successCallback(response) {
$scope.userLocation.push(response);
});
}
}])
问题:当我尝试向他们的 Places API 发出类似的 GET 请求时 - 我收到 CORS 错误:
Problem: When I try a similar GET request to their Places API - I get CORS errors:
XMLHttpRequest 无法加载 https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=36.23…5.1458888&type=bar&key=xxx.请求的资源上不存在Access-Control-Allow-Origin"标头.因此不允许访问源http://0.0.0.0:3000".
问题:我可以从 Angular 发出这些类型的请求,还是需要设置后端来进行调用?
Question: Am I able to make these types of requests from Angular or do I need to setup the backend to make that call instead?
我尝试使用 JSONP 作为方法,该方法通过了 CORS 问题,但随后出现无法访问数据的问题.不确定它是否是无效的 JSON...但它说 Unexpected identifier :
,当我查看源代码时,它对我来说看起来像是完美的数据:
I tried using JSONP as the method, which passed the CORS issue, but then I have the problem of not being able to access the data. Not sure if it's invalid JSON... but it says Unexpected identifier :
, and when I view the source it looks like perfectly fine data to me:
{
"html_attributions" : [],
"results" : [
{
"geometry" : {
"location" : {
"lat" : 36.2388477,
"lng" : -115.1540073
},
},
"icon" : "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
"id" : "578bfba1f17b0c5fbdafd5b71600b50d3e95c1ca",
"name" : "Ruby Tuesday",
"opening_hours" : {
"open_now" : true,
"weekday_text" : []
},
推荐答案
您可以通过 Google Maps JavaScript API 中包含的库在客户端使用 Places API.
You can use Places API on client side via the library included in Google Maps JavaScript API.
请参阅此页面以了解其工作原理:
Please refer to this page to figure out how it works:
https://developers.google.com/maps/documentation/javascript/places
否则,您必须创建后端服务器以向 Google 发送请求并将响应传递给您的客户端代码.
Otherwise, you have to create your backend server to send requests to Google and pass response to your client side code.
希望有帮助!
这篇关于CORS 和 Angular $http GET 到 Google Places API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!