【问题标题】:Using Bing maps REST from Angular failing even though 200 response returned即使返回 200 响应,使用 Bing 从 Angular 映射 REST 也会失败
【发布时间】:2015-01-07 04:30:13
【问题描述】:

我正在尝试从 Angular 中使用 Bing 地图 REST api。 Fiddler 为下面的两个请求显示了 200 响应,但 Angular 都失败了,带有“没有 Access-Control-Allow-Origin 标头存在”的 $hhtp 和带有“意外令牌:”的 $request

我之前没有尝试过使用 Angular 进行跨域请求,但显然我遗漏了一些东西。任何帮助将不胜感激。

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular.js"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.0/angular-resource.js"></script>
</head>
<body ng-app="myapp">
    <div ng-controller="myctrl"></div>
<script type="text/javascript">
var myapp = angular.module('myapp', ['ngResource']).config(['$httpProvider', function ($httpProvider) {
    // delete header from client:
    // http://stackoverflow.com/questions/17289195/angularjs-post-data-to-external-rest-api
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);
myapp.controller('myctrl', ["$scope", "$resource", "$http", function ($scope, $resource, $http) {
    var t = $resource('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&key=MAPKEY&o=json',
    {
        callback: 'JSON_CALLBACK'
    }, {
        jsonpquery: { method: 'JSONP', isArray: false }
    });
    var x = t.jsonpquery().$promise;
    debugger;
    x.then(function (data) {
        debugger;
        console.log(data);
    });

    $http.get('http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=jsonp&key=MAPKEY')
        .success(function(data) {
        debugger;
        })
        .error(function(data, status, error, thing) {
        debugger;
        console.log(data);
    });
}]);
</script>
</body>
</html>

您需要来自https://www.bingmapsportal.com/ 的映射键才能发出请求。 任何帮助表示赞赏,否则我将直接使用 jQuery

【问题讨论】:

    标签: angularjs rest bing-maps


    【解决方案1】:

    使用 $http.jsonp 而不是 $http.get。以下代码有效:

    var url = "http://dev.virtualearth.net/REST/v1/Locations?locality=Redmond&adminDistrict=WA&jsonp=JSON_CALLBACK&key=YOUR_BING_MAPS_KEY";
    
    $http.jsonp(url)
            .success(function (data) {
                debugger;
            })
        .error(function (data, status, error, thing) {
            debugger;
            console.log(data);
        });
    

    【讨论】:

      猜你喜欢
      • 2014-09-20
      • 2020-11-23
      • 1970-01-01
      • 2021-08-09
      • 2014-11-17
      • 1970-01-01
      • 2014-09-07
      • 2020-04-02
      • 1970-01-01
      相关资源
      最近更新 更多