【问题标题】:Access-Control-Allow-Origin when sending request to google api向 google api 发送请求时的 Access-Control-Allow-Origin
【发布时间】:2016-03-04 19:04:39
【问题描述】:

我试图在我的 angularjs 应用程序中向谷歌 API 发送一个请求,以获取某个位置周围半径内的景点。但我在 chrome 中收到此错误消息: 请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'http://localhost:9000' 因此不允许访问。

json 和 jsonp 我都试过了,但结果是一样的。 :S

    $http.get('https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>')
        .then(function(response) {
            $scope.dataResult = response.data;
        });
    $scope.getlocation = function() {

        $scope.method = 'GET';
        $http({ method: $scope.method, url: "https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&radius=5000&type=museum&key=<MYKEY>&callback=JSON_CALLBACK" }).
        success(function(data, status) {

            $scope.status = status;
            $scope.data = data;
            console.log(data);
        }).
        error(function(data, status) {
            $scope.data = data || "Request failed";
            $scope.status = status;
        });

    };

我不想在地图上显示结果,我只想要列表格式。

【问题讨论】:

  • 问题是你的起点是http,你的目的地是https。使两者相等。

标签: angularjs google-api


【解决方案1】:

这是 CORS 问题,您可以从客户端启用这样的 cors 请求。

angular.module('yourapp').config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }
]);

您的案例的问题是,https://maps.googleapis.com/maps/api/place/radarsearch/json?location=51.503186,-0.126446&amp;radius=5000&amp;type=museum&amp;key=&lt;MYKEY&gt; 不允许您的来源访问响应。因此,您无法阅读它。

我希望你有一个有效的密钥,并且在注册时你已经在域名的地方列出了你的本地主机......因为谷歌需要知道这些。

【讨论】:

  • 我已经为按键启用了localhostlocalhost:9000/#localhost:9000。如果我检查 Google Places API Web Service,我会看到请求随着每个请求而增加。并且还启用了服务 api。
  • @JediSchmedi:你能把上面的东西添加到你的配置中并检查它是否工作。
  • 这是 app.js .config(function($routeProvider, $httpProvider) { $httpProvider.defaults.useXDomain = true; $httpProvider.defaults.withCredentials = true; 删除 $httpProvider.defaults.headers .common["X-Requested-With"]; $httpProvider.defaults.headers.common["Accept"] = "application/json"; $httpProvider.defaults.headers.common["Content-Type"] = "application /json";
  • 你能试试这里的例子之一并分享...developers.google.com/api-client-library/javascript/features/…
猜你喜欢
  • 2021-03-17
  • 2014-02-01
  • 2017-08-01
  • 2013-12-21
  • 1970-01-01
  • 2016-08-03
  • 2018-03-28
  • 2011-09-01
相关资源
最近更新 更多