CORS on api of Codechef (using angularjs) - javascript

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.

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.

Related

'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)

I'm getting an a "XMLHttpRequest cannot load https://example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access."
This is my componenDidMount(), and I'm using axios to get the data from my API.
componentDidMount() {
this.serverRequest = axios.get(this.props.source).then(event =>{
this.setState({
title: event.data[0].name
});
});
}
I'm using "python -m SimpleHTTPServer" on the terminal, to run 'http://localhost:8000'.
I'm using the Chrome browser, and if I turn on the Chrome CORS plugin (to enable cross origin resource sharing), the app works, and I see data displayed from the API on the DOM. But I know that using the CORS plugin is bad, so how should I fix the 'Access-Control-Allow-Origin' error officially?
With Axios, can I somehow add dataType: "jsonp", if that would fix it?
This is a restriction made by the browser for security reasons when you try to access content in some domain from another domain. You overcome this, you need to set the following in your header
Access-Control-Request-Method
Access-Control-Request-Headers
Many sites restrict CORS. The best way to achieve your goal is to make your python server as a proxy. See the example.
//Request from the client/browser
http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com
//In your server
1. Handle the request
2. Get the query param(url of the website)
3. Fetch it using your python server
4. Return the fetching data to the client.
This should work.

How to make cross origin get request via angularjs http using food2fork api

I'm simply trying to make a get request using food2fork's search api in an angular app. Right now I've got no backend to the app, so everything is running client side, and I'm running the following (with the APIKEY replaced, of course):
$http.jsonp('http://food2fork.com/api/search?q=turkey&key=APIKEY&callback=jsonp_callback')
.then(function(response) {
console.log(response);
});
However, I'm Uncaught SyntaxError: Unexpected token : in the console. I assume this is because it's expecting a jsonp function rather than json.
If I run it as a jquery getJSON, as seen here:
$(document).ready(function() {
var url = "http://food2fork.com/api/search?q=turkey&key=APIKEY";
$.getJSON(url,function(data) {
})
});
I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. - which may be because I'm running locally, but that hasn't been a problem in the past.
I just want to get the json that I get if I run the same request as a url in a browser. Any ideas?
No 'Access-Control-Allow-Origin' header is present on the requested resource
You are facing Cross Domain problem and what you should do is enabling CORS from your server side (the service running from localhost:8080)

Cannot POST data cross domain in Angular app

EDIT:
Problem is resolved. My front end code is fine, it's error of back end guys.
I have problem when POST data cross domain. I don't know why, just 3 hours ago it worked fine. At that time I just made some changes in CSS and HTML, I was not touch to any JS file. I also asked the Back end team (They're using Ruby on Rails) and they told me that they still working on localhost.
This error appear every time I try to POST to server when using both Firefox and Chrome:
XMLHttpRequest cannot load https://time-traveler-back.herokuapp.com/api/sessions/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access. The response had HTTP status code 503.
For Chrome, I already installed CORS app. But if I turned it on, another error appear:
XMLHttpRequest cannot load https://time-traveler-back.herokuapp.com/api/sessions/login. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'http://localhost:9000' is therefore not allowed access.
Here is my app config:
// Config for POST data cross domain
app.config(['$routeProvider', '$httpProvider', function($routeProvider, $httpProvider) {
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "application/json";
$httpProvider.defaults.headers.common["Content-Type"] = "application/json";
}]);
This is how I POST data:
var apiUrl = 'https://time-traveler-back.herokuapp.com/api/';
$http({
method: 'POST',
url: apiUrl + 'sessions/login',
data: $.param(formData), // pass in data as strings
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
} // set the headers so angular passing info as form data (not request payload)
})
.then(function successCallback(response) {
// my stuffs
}, function errorCallback(response) {
// my stuffs
});
Please help me. Thanks.
Credentials and CORS
One thing to note when using withCredentials: true in your app and
configuring the server for CORS is that you may not have your
Access-Control-Allow-Origin header set to '*'. It must be configured
to a few select origins. If you absolutely must have this set to *,
then I suggest doing something beyond cookie based authentication,
such as token-based authentication.
See AngularJS Authentication and CORS
Looks like a standard CORS error.
You already fixed, but in case of doubt, I'll give some recommendations:
Rack-CORS
If using rails as the backend, you should definitely check out the rack-cors gem. This basically sets up all the CORS policies for your server through the middleware in the most simple way possible:
#config/application.rb
...
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :options]
end
end
This allows you to permit particular domains "origins" & methods to your app.
--
You must also remember that to prevent cross domain XML requests, "CORS" (Cross Origin Resource Sharing) was instituted to apply a "lock" on which resources / urls are accessible by JS requests.
As a rule of thumb, if you're ever using JS to automagically update the front-end with an XML request of a separate domain (not just Ajax), you'll need to permit the domain in your server's CORS policy.
There are a number of ways to do this; simplest with rails is to use the rack-CORS gem (as above).

CORS error in AngularJS

When I am using Fiddler or any browser side HTTP client extension like Advanced Rest Client, I can get data from a API easily.
But when I try to use the same API from Angular JS, CORS issue appear immediately. I have tried with following lines to solve the problem in AngularJS, But unfortunately it did not work.
appd.config(function ($httpProvider) {
// $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// $httpProvider.defaults.headers.post['Accept'] = '*/*'
$httpProvider.defaults.useXDomain = true;
$httpProvider.defaults.withCredentials = true;
delete $httpProvider.defaults.headers.common["X-Requested-With"];
$httpProvider.defaults.headers.common["Accept"] = "*/*";
$httpProvider.defaults.headers.common["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.headers.common['Authorization'] = 'Basic encodedpassword=';
});
I get following error in mozilla:
Cross-Origin Request Blocked:
The Same Origin Policy disallows reading the remote resource at http://host/training_webapi. This can be fixed by moving the resource to the same domain or enabling CORS.
And following in Chrome:
XMLHttpRequest cannot load http://host/training_webapi The request was redirected to 'http:host/training_webapi/', which is disallowed for cross-origin requests that require preflight.
The service you are requesting is not allowing CORS (no Access-Control are sent as part of the response).
You would need to include the header Access-Control-Allow-Origin: * as part of the response (which it does not).
See this : http://www.html5rocks.com/en/tutorials/cors/
You might be able to use $http.jsonp.
var url = "http://host/training_webapi?callback=JSON_CALLBACK";
$http.jsonp(url)
.success(function(data){
console.log(data.found);
});
Working JSFiddle
Another option (since you don't own the server), could be to proxy the request on your server and access that URI using angular.
One more point, in your code the content header is set to form:
$httpProvider.defaults.headers.common["Content-Type"] = "application/x-www-form-urlencoded";
Your request should be expecting
content-type: application/json

ADAL - JavaScript used in Angular JS in SPA app , to call third party APIs exposed through APIGEE giving CORS error

I have created a SPA and used Azure AD for User store and ADAL-JavaScript library as mentioned on a http://www.cloudidentity.com/blog/2014/10/28/adal-javascript-and-angularjs-deep-dive/ to integrate with my angular js code. It did authentication flow successfully, but when I was calling the third party API exposed using APIGEE, I was getting following error messages:
Failed to load resource: the server responded with a status of 502 (Bad Gateway)
XMLHttpRequest cannot load http: //webapiexposedusingapigee. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://mywebsite.in' is therefore not allowed access. The response had HTTP status code 502.
When I checked in Fiddler i got following fault string.
"faultstring=Received 405 Response without Allow Header"
and warning as :
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http:// test.apigee.net/v1/selectop/myapi. This can be fixed by moving the resource to the same domain or enabling CORS.
I had added following headers on APIGEE:
<Header name="Access-Control-Allow-Origin">*</Header>
<Header name="Access-Control-Allow-Credentials">true</Header>
<Header name="Access-Control-Allow-Headers">Origin, X-Requested-With, Content-Type, Accept</Header>
<Header name="Access-Control-Max-Age">3628800</Header>
<Header name="Access-Control-Allow-Methods">GET, PUT, POST, DELETE, OPTION</Header>
Any help on this is appreciated.
Thanks.
If you have correct CORS setup at WebAPI endpoint, it will accept the request. I am not familiar with APIGEE, but this link lists the steps to enable:http://apigee.com/docs/api-services/content/adding-cors-support-api-proxy.
You need to specify to use xdomain to send headers in angular js:
app.factory('contactService', ['$http', function ($http) {
var serviceFactory = {};
var _getItems = function () {
$http.defaults.useXDomain = true;
delete $http.defaults.headers.common['X-Requested-With'];
return $http.get('http://adaljscors.azurewebsites.net/api/contacts');
};
serviceFactory.getItems = _getItems;
return serviceFactory;
}]);

Categories

Resources