Dylan
Dylan

Reputation: 1306

Using Bing maps REST from Angular failing even though 200 response returned

I'm trying to use the Bing maps REST api from within angular. Fiddler shows a 200 response for both requests below, but Angular fails both, the $hhtp with "No Access-Control-Allow-Origin header is present' and the $request with "Unexpected token : "

I've not tried to do a cross-origin request with angular before but clearly I'm missing something. Any help would be appreciated.

<!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>

You'll need a map key from https://www.bingmapsportal.com/ to make a request though. Any help appreciated, otherwise I'll drop down to using jQuery

Upvotes: 0

Views: 1211

Answers (1)

rbrundritt
rbrundritt

Reputation: 18003

Use $http.jsonp instead of $http.get. The following code works:

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);
    });

Upvotes: 2

Related Questions