【问题标题】:CORS on api of Codechef (using angularjs)Codechef api上的CORS(使用angularjs)
【发布时间】:2021-08-12 18:54:14
【问题描述】:

以下网址以 JSON 格式给出任何比赛的排名 https://www.codechef.com/api/rankings/OCT17 只需将 OCT17 替换为任何比赛代码

我想制作一个 Web 应用程序来获取此 api 并显示自定义排行榜。我尝试使用 angularjs,但它是 CORS 错误

这是代码

var app = angular.module('Ranklist', []);
app.config(['$httpProvider', function($httpProvider) {
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
        console.log("cross origin allowed");
    }
]);
app.controller('rank',function($scope,$http){
    var uri = 'https://www.codechef.com/api/rankings/COPH2017?sortBy=rank&order=asc&page=1&itemsPerPage=25';
    $scope.test = "test data";
    console.log("love can hear")
    $http.get(uri)
        .then(function(response){
        $scope.data = response.data; 
    });
});

控制台在 chrome 中显示这 2 个错误

Failed to load https://www.codechef.com/api/rankings/COPH2017?sortBy=rank&order=asc&page=1&itemsPerPage=25: The 'Access-Control-Allow-Origin' header has a value 'https://developers.codechef.com that is not equal to the supplied origin. Origin 'http://127.0.0.1:58502' is therefore not allowed access.```

angular.js:14525 Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"https://www.codechef.com/api/rankings/COPH2017?sortBy=rank&order=asc&page=1&itemsPerPage=25","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}

在 IE 上没有错误,而在 chrome 上 这可以修复还是只是服务器端问题(或他们的偏好)

我也试过 $http.jsonp() 函数。

【问题讨论】:

    标签: javascript angularjs http cors


    【解决方案1】:

    您不能在客户端浏览器上发出跨域请求 (CORS)。

    此 API 只允许来自 https://developers.codechef.com 的请求

    鉴于您的请求不是来自该域,您将被拒绝访问。

    CORS 仅由浏览器强制执行。因此,如果您有自己的后端服务器并向该服务器发出请求,并且您的服务器从他们的服务器发出请求(称为代理请求),那么您会很好,因为您将避免 CORS 问题。

    【讨论】:

      猜你喜欢
      • 2016-03-23
      • 2014-10-19
      • 2014-06-01
      • 2019-03-25
      • 1970-01-01
      • 2015-02-21
      • 2017-02-19
      • 2016-06-21
      • 2013-05-21
      相关资源
      最近更新 更多