【发布时间】: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
【问题讨论】: