Angular,使用jsonp绕过'允许访问来源'

时间:2015-10-20 15:01:56

标签: javascript json angularjs cors

尝试使用外部API。

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

我得到的错误是:

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.

我无法将API配置为从不同的域接受。相反,我尝试使用jsonp

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

如果我检查chrome dev工具中的网络选项卡,我可以看到正确的200 OK回复数据。

但有角度的推出:Unexpected token :

这是因为角度预期" json回调"。无论如何我可以从客户端解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

您需要将回调的名称用作“JSON_CALLBACK”。

请参考以下代码 -

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>