0

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

1 Answer 1

3

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 any headers 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
});

Not So Simple Request

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.