AngularJS CORS http 调用不工作但普通 Ajax & jQuery 工作正常

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

我有一个简单的跨域服务,旨在处理 Simple CORS request。我可以通过纯 xmlHTTP 调用或 jQuery($.ajax) 来调用它,但它抛出 Access-Control-Allow-Origin 错误 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 动词)但使用普通 Ajax 调用或 jQuery Ajax 其作为 non-preflighted CORS 请求发送,由调试器网络选项卡确认在 chrome.

作为设计用于处理简单 CORS 请求调用的服务,我们需要确保 Angular 也以某种方式准备请求,以便浏览器发出简单的 CORS 请求(参见 Simple 与 MDN ).

上的 Not so simple CORS 请求

解决方法: 参考Access-Control-Request-Headers[=去掉Angular添加的headers 19=]

GET request without any headers is treated as simple request

如果你配置了 Angular $http defaults,它会把这些 headers 添加到请求中,这使得 没那么简单 CORS 如下图所示。

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