CORS全部来自客户端的角度js $ http请求

时间:2018-01-09 18:05:08

标签: javascript angularjs json cors

当我从浏览器调用此URL tweeter follower count时,我收到了JSON响应。但由于角度JS代码不允许进行CORS验证。

我需要一个没有服务器修改的AngularJS解决方案。因为浏览器给我一个正确的结果,我认为angularJS代码应该给出正确的结果。我正在使用有角度的 1.4.7 库。

这是我的代码:

var homeApp = angular.module('routerApp.home',[])
.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.headers.common = 'Content-Type: 
    application/json';
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
])
.controller('homeController',homeController);

 homeController.$inject = ['$window', '$scope','homeService'];

 function homeController($window,$scope,homeService) {

 var followers = homeService.getFollowersOfTweeter();
 followers.then(function (response) {
         $scope.followers =12; /*response[0].followers_count;
         console.log(response)*/ },
     function (reason) {

     })

};

和服务js在这里

homeApp.factory('homeService', homeService)
homeService.$inject = ['$http', '$q', '$timeout'];

function homeService($http, $q, $timeout) {

function getFollowersOfTweeter() {
    var headers = {
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'POST, GET, OPTIONS, PUT',
        'Access-Control-Allow-Headers' : 'Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization'
    };
    return $http({
        url: 'https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=sanjoykdeb',
        method: "GET",
        headers: headers
    })
        .then(function (response) {
            console.log('Here')
            console.log(JSON.stringify(response));
            return JSON.stringify(response);
        }, function (reason) {
            return null;
        });
}

return {
    getFollowersOfTweeter: getFollowersOfTweeter
};

}

我在浏览器控制台上遇到错误

Failed to load https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=sanjoykdeb: Response to a preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access. The response had HTTP status code 400.

0 个答案:

没有答案