Access-Control-Allow-Origin 不允许 $http.get,但 $.ajax 允许

2023-12-02

我在从我控制的远程服务器获取 json 时遇到问题。我有 2 个 Web 应用程序,一个提供数据并在端口 3311 上运行,另一个请求数据并在端口 5000 上运行。

使用jquery进行以下工作:

$.ajax({
  url: "http://localhost:3311/get-data",
  type: 'GET',
  dataType: 'json',
  beforeSend: function(xhr) {
    xhr.setRequestHeader("x-some-header", "some-value");
  }
})
.done(function(data) { 
    $rootScope.$apply(function() {d.resolve(data); });
})
.fail(function(data) {
    $rootScope.$apply(function() {d.reject(data); });
});

当尝试使用角度相同的获取请求时

$http
    .get("http://localhost:3311/get-data", { headers: {"x-some-header": "some-value"} })
    .success(function(data) { d.resolve(data);})
    .error(function(data) { d.reject(data); });

我收到错误

Origin http://localhost:5000 is not allowed by Access-Control-Allow-Origin.

控制台日志显示 OPTIONS 请求返回 HTTP200 后发生错误

OPTIONS http://localhost:3311//get-data 200 (OK) angular.min.js:99

(anonymous function) angular.min.js:99

l angular.min.js:95

m angular.min.js:94

(anonymous function) app.js:78

b.extend.each jquery-1.9.1.min.js:3

b.fn.b.each jquery-1.9.1.min.js:3

(anonymous function) app.js:76

d angular.min.js:28

instantiate angular.min.js:28

(anonymous function) angular.min.js:52

updateView angular-ui-states.js:892

e.$broadcast angular.min.js:90

transition angular-ui-states.js:324

h angular.min.js:77

(anonymous function) angular.min.js:78

e.$eval angular.min.js:88

e.$digest angular.min.js:86

e.$apply angular.min.js:88

e angular.min.js:94

o angular.min.js:98

s.onreadystatechange angular.min.js:99

从 OPTIONS 请求返回的标头是

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/plain
Server: Microsoft-IIS/8.0
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Headers: Content-Type, Accept, X-Requested-With, x-some-header
X-AspNet-Version: 4.0.30319
X-SourceFiles: =?UTF-8?B?....
X-Powered-By: ASP.NET
Date: Tue, 21 May 2013 01:52:37 GMT
Content-Length: 0

这可能是由于 Angular 包含请求标头的默认行为'X-Requested-With',这可能会导致 CORS 问题。这已在 v 1.1.1 中修复(不稳定分支 -请参阅 v1.1.1 错误修复)通过从跨域请求中删除标头:https://github.com/angular/angular.js/issues/1004.

删除标头并使其在 1.0 分支上运行很容易。以下行将从应用程序中的 $http 服务完成的所有请求(不仅是 CORS)中删除标头:

yourModule
  .config(function($httpProvider){
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
});

Update一个小警告 - Angular(如 jQuery)不支持 IE9 的 CORS。 IE10是第一个支持CORS的IE浏览器。这篇博文描述了如何在某些条件下在 IE8/IE9 中获得 CORS 支持,但它不适用于 Angular $http 服务:http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Access-Control-Allow-Origin 不允许 $http.get,但 $.ajax 允许 的相关文章