Issue
The following url gives the ranking of any contest in JSON format https://www.codechef.com/api/rankings/OCT17 Just replace OCT17 with any contest code
I thought of making a web app which will fetch this api and display a custom leaderboard.I tried using the angularjs but it is CORS error
This is code
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;
});
});
Console is showing these 2 errors in chrome
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.```
and
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":""}
There is no error on IE while there is on chrome Can this be fixed or it is just a server side problem(or their preference)
I also tried $http.jsonp() function.
Solution
You cannot make a cross domain request (CORS) on the client browser.
This API only allows requests from https://developers.codechef.com
Given that your request is not coming from that domain you are being denied access.
CORS is only enforced by the browser. Therefore, if you have your own backend server and make a request to that server and your server requests from their server (known as proxying the request) you will be fine since you will avoid the CORS problem.
Answered By - danday74
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.