-1

Trying to use an external API.

$http({method: 'json', url: url })
      .then(function(data){
        console.log(data);
      }, function(err, code){
        console.log(err);
      })

The error I get is:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access. The response had HTTP status code 401.

I can't configure the API to accept from a diffrent domain. Instead I try to use jsonp.

$http({method: 'jsonp', url: url })

If I check the network tab in chrome dev tools I can see a properly recived 200 OK response with the data.

But angular puts out: Unexpected token :

This is because angular expects "json callback". Is there anyway I can fix this from the client side?

Joe
  • 4,274
  • 32
  • 95
  • 175
  • 2
    Nope. can't fix it using just the browser, you'll need a server, somewhere (not necessarily your own) to interpret the json and convert it to jsonp. – Kevin B Oct 20 '15 at 15:08
  • Possible duplicate of [AngularJS: how to make a jsonp request](http://stackoverflow.com/questions/19916362/angularjs-how-to-make-a-jsonp-request) – Danmoreng Oct 20 '15 at 15:09
  • or consider adding a CORS header http://www.html5rocks.com/en/tutorials/cors/ – Shanimal Oct 20 '15 at 15:17

1 Answers1

0

You need to use the name of the callback as "JSON_CALLBACK".

Please refer code as below -

angular.module('alertApp', ['alertApp.controllers','alertApp.services']);

angular.module('alertApp.services', []).factory('alertAPIservice', function($http) {
var alertAPI = {};
alertAPI.getAlerts = function() {
  return $http.jsonp('https://angularjs.org/greet.php?name=StackOverflow&callback=JSON_CALLBACK');
  //use &callback=JSON_CALLBACK' in url
}
 return alertAPI;
});

angular.module('alertApp.controllers', [])
.controller('mainController', function($scope, alertAPIservice) {
    $scope.message = 'Hello Mid-World!';
    $scope.alertsList = "loading data";

    alertAPIservice.getAlerts().then(function (response) {
        $scope.alertsList = response.data;
    },function(error,a,b){
        $scope.alertsList = error;
    });  

}); 
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body ng-app="alertApp">
<div ng-controller="mainController">
  {{message}}

  <div>
    <pre>{{alertsList|json}}</pre>
  </div>
</div>
</body>
Manoj Shevate
  • 742
  • 4
  • 18