我试图从角度内使用Bing地图REST api。 Fiddler对下面的两个请求都显示了200个响应,但Angular都失败了,带有" No Access-Control-Allow-Origin标头的$ hhtp存在'和#34;意外令牌的$ request:"
我之前没有尝试过使用棱角分明的原始请求,但显然我错过了一些东西。任何帮助将不胜感激。
<!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
答案 0 :(得分:2)
使用$ 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);
});