Javascript Google Place API - 请求的资源上不存在“Access-Control-Allow-Origin”标头。因此不允许访问原点 'null'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28359730/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:40:33  来源:igfitidea点击:

Google Place API - No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access

javascriptjqueryajaxgoogle-mapsgoogle-places-api

提问by Abrar Jahin

I am using Google Place API.

我正在使用 Google Place API。

What I want to get suggestion of place for type helping.

我想得到关于打字帮助的地方的建议。

So, what I have done is-

所以,我所做的是——

var Google_Places_API_KEY = "AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM";      //Get it from - https://code.google.com/apis/console/?noredirect#project:647731786600:access
var language = "en";        //'en' for English, 'nl' for Nederland's Language


var Auto_Complete_Link = "https://maps.googleapis.com/maps/api/place/autocomplete/json?key="+Google_Places_API_KEY+"&types=geocode&language="+language+"&input=Khu";
$.getJSON(Auto_Complete_Link , function(result)
{
    $.each(result, function(i, field)
    {
        //$("div").append(field + " ");
        //alert(i + "=="+ field);
        console.error(i + "=="+ field);
    });
});

So in what link I am requesting is -

所以在我请求的链接中是 -

https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM&types=geocode&language=en&input=Khu

https://maps.googleapis.com/maps/api/place/autocomplete/json?key=AIzaSyAK08OEC-B2kSyWfSdeCzdIkVnT44bcBwM&types=geocode&language=en&input=Khu

And if I go to this link with browser, I can get output like it (please try to ck)-

如果我使用浏览器访问此链接,我可以获得类似的输出(请尝试 ck)-

11

11

But if I try with jQuery's .getJSONor .ajax, I am getting my request blocked with this message-

但是,如果我尝试使用 jQuery 的.getJSON.ajax,我的请求会被此消息阻止-

222.

222.

SO the XMLHTTPRequest is blocked because of -

所以 XMLHTTPRequest 被阻止,因为 -

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。

I have checked in StackOverflowfor this problem solution and go through hereand here, but can't get my solution perfectly.

我已经在StackOverflow 中检查了这个问题的解决方案,并通过了这里这里,但无法完美地得到我的解决方案。

Can anyone please enlighten me?

任何人都可以请教我吗?

采纳答案by Outlooker

AJAX Requests are only possible if port, protocol and domain of sender and receiver are equal,if not might lead to CORS. CORS stands for Cross-origin resource sharing and has to be supported on the server side.

AJAX 请求只有在发送方和接收方的端口、协议和域相等时才可能,否则可能导致 CORS。CORS 代表跨域资源共享,必须在服务器端支持。

Solution

解决方案

JSONP

JSONP

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy.

JSONP 或“带填充的 JSON”是一种通信技术,用于在 Web 浏览器中运行的 JavaScript 程序,以从不同域中的服务器请求数据,由于同源策略,典型的 Web 浏览器禁止这种技术。

Something like this might help you mate.. :)

像这样的事情可能会帮助你交配.. :)

$.ajax({
            url: Auto_Complete_Link, 
            type: "GET",   
            dataType: 'jsonp',
            cache: false,
            success: function(response){                          
                alert(response);                   
            }           
        });    

回答by Sgedda

I got it working after finding answer by @sideshowbarker here:

我在这里找到@sideshowbarker 的答案后开始工作了:

No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

请求的资源上不存在“Access-Control-Allow-Origin”标头——尝试从 REST API 获取数据时

And then used this approach to get it working:

然后使用这种方法让它工作:

const proxyurl = "https://cors-anywhere.herokuapp.com/";
const url = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=${latitude},${longitude}&radius=500&key=[API KEY]"; // site that doesn't send Access-Control-*
fetch(proxyurl + url) // https://cors-anywhere.herokuapp.com/https://example.com
.then(response => response.json())
.then(contents => console.log(contents))
.catch(() => console.log("Can't access " + url + " response. Blocked by browser?"))

More info can be found in the answer in link above.

更多信息可以在上面链接的答案中找到。

回答by Subendra Sharma

ok so this is how we do it in javascript... google have their own functions for this....

好的,这就是我们在 javascript 中的做法……谷歌对此有自己的功能……

link: https://developers.google.com/maps/documentation/javascript/places#place_search_requests

链接:https: //developers.google.com/maps/documentation/javascript/places#place_search_requests

var map;
var service;
var infowindow;

function initialize() {
  var pyrmont = new google.maps.LatLng(-33.8665433,151.1956316);

  map = new google.maps.Map(document.getElementById('map'), {
      center: pyrmont,
      zoom: 15
    });

  var request = {
    location: pyrmont,
    radius: '500',
    types: ['store']
  };

  service = new google.maps.places.PlacesService(map);
  service.nearbySearch(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}

anyone wants to gain access to the place Id and stuff this is how we do it.... In the call back function we have the JSONArray of places returned by google... In the call back function inside the for loop after the line var place = results[i];u can get wat u want like

任何人都想获得对地点 ID 的访问权,这就是我们如何做到的......在回调函数中,我们有谷歌返回的地点的 JSONArray......var place = results[i];你可以得到你想要的

console.log(place.name);
console.log(place.place_id);
var types = String(place.types);
types=types.split(",");
console.log(types[0]);

回答by S.D.

Google provides API Client library:

谷歌提供 API 客户端库:

<script src="https://apis.google.com/js/api.js" type="text/javascript"></script>

It can do google API requests for you, given the API path and parameters:

给定 API 路径和参数,它可以为您执行 google API 请求:

var restRequest = gapi.client.request({
  'path': 'https://people.googleapis.com/v1/people/me/connections',
  'params': {'sortOrder': 'LAST_NAME_ASCENDING'}
});

Since the library is served from google domain, it can safely call google API's without CORS issues.

由于库是从 google 域提供的,因此它可以安全地调用 google API,而不会出现 CORS 问题。

Google docs on how to use CORS.

关于如何使用 CORS 的 Google 文档。

回答by Eric Reynolds

I was able to solve the problem by creating a PHP file on the same server as my javascript file. Then using cURL to get the data from Google and send it back to my js file.

我能够通过在与我的 javascript 文件相同的服务器上创建一个 PHP 文件来解决这个问题。然后使用 cURL 从 Google 获取数据并将其发送回我的 js 文件。

PHP File

PHP文件

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://maps.googleapis.com/maps/api/place/textsearch/xml?query=" . $_POST['search'] . "&key=".$api);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
echo $output;

Javascript File

Javascript文件

var search = encodeURI($("#input_field").val());
$.post("curl.php", { search: search }, function(xml){
  $(xml).find('result').each(function(){
    var title = $(this).find('name').text();
    console.log(title);
  });
});

With this solution I don't get any CORS errors.

使用此解决方案,我不会收到任何 CORS 错误。

回答by EthanChou

There's no way in client side we using ajaxfetching Google Place API, neither use jsonp(syntax error :) nor we met cors issue,

我们在客户端无法使用ajaxfetching Google Place API,既不使用jsonp(语法错误:) 也不遇到 cors 问题,

The only way in client side is using Google Javascript Library instead https://developers.google.com/maps/documentation/javascript/tutorial

客户端的唯一方法是使用 Google Javascript 库代替 https://developers.google.com/maps/documentation/javascript/tutorial

Or you can fetch google place api in server side, then create your own api for your client side.

或者您可以在服务器端获取 google place api,然后为您的客户端创建自己的 api。

回答by lakme.1989

I accessed the google maps API like this

我像这样访问了谷歌地图 API

    $scope.getLocationFromAddress = function(address) {
    if($scope.address!="Your Location"){
        $scope.position = "";
        delete $http.defaults.headers.common['X-Requested-With'];
        $http(
                {
                    method : 'GET',
                    url : 'https://maps.googleapis.com/maps/api/geocode/json?address='+ address+'&key=AIzaSyAAqEuv_SHtc0ByecPXSQiKH5f2p2t5oP4',

                }).success(function(data, status, headers, config) {

            $scope.position = data.results[0].geometry.location.lat+","+data.results[0].geometry.location.lng;                              
        }).error(function(data, status, headers, config) {
            debugger;
            console.log(data);
        });
    }
}

回答by Nadimuthu Sarangapani

Hi,

你好,

Please try with Google distance matrix

请尝试使用谷歌距离矩阵

    var origin = new google.maps.LatLng(detectedLatitude,detectedLongitude);       
    var destination = new google.maps.LatLng(latitudeVal,langtitudeVal);
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: 'DRIVING',            
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
      }, response_data);

      function response_data(responseDis, status) {
      if (status !== google.maps.DistanceMatrixStatus.OK || status != "OK"){
        console.log('Error:', status);
        // OR
        alert(status);
      }else{
           alert(responseDis.rows[0].elements[0].distance.text);
      }
  });

If you are using JSONP, sometimes you will get missing statement error in the CONSOLE.

如果您使用的是 JSONP,有时您会在 CONSOLE 中看到缺少语句错误。

Please refer this document click here

请参阅此文档,请单击此处