AngularJS CORS http 调用不起作用,但普通的 Ajax 和 jQuery 工作正常
Posted
技术标签:
【中文标题】AngularJS CORS http 调用不起作用,但普通的 Ajax 和 jQuery 工作正常【英文标题】:AngularJS CORS http call not working but plain Ajax & jQuery working fine 【发布时间】:2018-12-18 01:04:50 【问题描述】:我有一个简单的跨域服务,旨在处理Simple CORS request。我可以通过普通的 xmlHTTP 调用或 jQuery($.ajax) 来调用它,但它使用 AngularJS $http
抛出 Access-Control-Allow-Origin 错误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】:通过 Angular $http 调用的CORS 请求触发了preflight(OPTIONS 动词),但使用纯 Ajax 调用或 jQuery Ajax 作为非预检 CORS 请求发送,已由 chrome 中的调试器网络选项卡确认。
作为旨在处理简单 CORS 请求调用的服务,我们需要确保 Angular 也以某种方式准备请求,以便浏览器发出简单的 CORS 请求(参见 Simple 与 MDN 上的不那么简单的 CORS 请求)。
解决方法:通过引用Access-Control-Request-Headers
来移除Angular添加的headers没有任何
headers
的GET
请求被视为简单请求
如果您配置了 Angular $http 默认值,它会将这些标头添加到请求中,这使得它不那么简单 CORS,如下图所示。
预检时所有自定义 HTTP 标头都以
Access-Control-Request-Headers
形式发送。一旦服务器允许按照 CORS 规则进行通信,浏览器就会发送实际请求(带有原始方法和标头等)
//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
);
【讨论】:
以上是关于AngularJS CORS http 调用不起作用,但普通的 Ajax 和 jQuery 工作正常的主要内容,如果未能解决你的问题,请参考以下文章
即使 CORS 不允许标头值,Angularjs 也会继续进行服务器调用
从 angularjs 调用 REST 服务时本地主机上的 CORS 问题
如果我使用XMLhttprequest调用API,它可以正常工作。但是当我使用angularjs(1.5.6)时,我得到了CORS错误