Reputation: 1517
I have a simple cross domain service designed to handle the Simple CORS request. I am able to call it through plain xmlHTTP call or jQuery($.ajax) but its throwing Access-Control-Allow-Origin error with AngularJS $http
var url = 'http://some-cross-domain-url/some-path';
$http.get(url); //preflight OPTION verb issued by browser and
//since server is not expecting it, it failed
$.ajax(url, {type: 'GET'}); //working fine as no preflight request sent
Upvotes: 0
Views: 576
Reputation: 1517
CORS request called via Angular $http was triggering preflight (OPTIONS verb) but with plain Ajax call or jQuery Ajax its sent as non-preflighted CORS request as confirmed by debugger network tab in chrome.
As the service designed to handle the Simple CORS request call we need to ensure that Angular also prepare request in a way so that browser issue simple CORS request (See Simple vs Not so simple CORS request at MDN).
Solution: Remove the headers added by Angular by referring Access-Control-Request-Headers
GET
request without anyheaders
is treated as simple request
If you have configured Angular $http defaults, it will add these headers into request which makes it not so simple CORS as shown in below image.
All custom HTTP headers sent as
Access-Control-Request-Headers
when preflighted. Once server allows the communication as per CORS rule, browser sends the actual request(with original Method and Headers etc)
//remove custom headers by looking at Access-Control-Request-Headers
var headers = {
'Authorization': undefined,//undefined tells angular to not to add this header
'pragma': undefined,
'cache-control': undefined,
'if-modified-since': undefined
};
$http.get(url, {
headers: headers
});
Upvotes: 3