【问题标题】:AngularJS CORS http call not working but plain Ajax & jQuery working fineAngularJS CORS http 调用不起作用,但普通的 Ajax 和 jQuery 工作正常
【发布时间】: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

【问题讨论】:

    标签: javascript jquery angularjs cors angularjs-http


    【解决方案1】:

    通过 Angular $http 调用的CORS 请求触发了preflight(OPTIONS 动词),但使用纯 Ajax 调用或 jQuery Ajax 作为非预检 CORS 请求发送,已由 chrome 中的调试器网络选项卡确认。

    作为旨在处理简单 CORS 请求调用的服务,我们需要确保 Angular 也以某种方式准备请求,以便浏览器发出简单的 CORS 请求(参见 Simple 与 MDN 上的不那么简单的 CORS 请求)。

    解决方法:通过引用Access-Control-Request-Headers

    来移除Angular添加的headers

    没有任何headersGET 请求被视为简单请求

    如果您配置了 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
    });

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-09-23
      • 2011-01-20
      • 2021-06-13
      • 2013-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多