简体   繁体   中英

AngularJS CORS http call not working but plain Ajax & jQuery working fine

I have a simple cross domain service designed to handle the Simple CORS reques t. 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 

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

要求不是那么简单

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM