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

时间:2013-05-21 02:01:41

标签: ajax angularjs cors

从我控制的远程服务器获取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); });
});

使用angular

尝试相同的get请求时
$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

4 个答案:

答案 0 :(得分:51)

这可能是由于Angular的默认行为包含请求标头'X-Requested-With',这可能会导致CORS出现问题。通过从跨域请求中删除标头see v1.1.1 bug fixes,修复了v 1.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'];
});

<强>更新 一点点警告 - 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

答案 1 :(得分:2)

web.config

<system.webServer> 
<httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
   </httpProtocol>
  </system.webServer>

答案 2 :(得分:0)

上面的答案解决了这个问题。

<httpProtocol>
    <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
     </customHeaders>
</httpProtocol>

当HTML页面使用如下服务调用角度控制器时:

$http.get(dataUrl).success(function (data) {
     $scope.data.products = data;
})
.error(function (error) {
    $scope.data.error = error;
});

答案 3 :(得分:0)

必须在服务器端设置请求的标头。 设置此

有很多种方法

1.One可以

 <filter>
   <filter-name>ResponseFilter</filter-name>
   <filter-class>org.apache.catalina.filters.CorsFilter</filter-class>
 </filter>
 <filter-mapping>
   <filter-name>ResponseFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>

2.独立于服务器,您可以开发一个可以作为init参数传递给jersey servlet的自定义类              com.sun.jersey.spi.container.ContainerResponseFilters         helpers.TestCorpsFilter             enter code here     `public class TestCorpsFilter实现了ContainerResponseFilter {

    @Override
    public ContainerResponse filter(ContainerRequest arg0, ContainerResponse arg1) {
        ResponseBuilder resp = Response.fromResponse(arg1.getResponse());
        resp.header("Access-Control-Allow-Origin", "*").header("Access-Control-Allow-Methods",
                "GET, POST, OPTIONS");

        String requestHeader = arg0.getHeaderValue("Access-Control-Request-Headers");

        if (requestHeader != null && !requestHeader.equals("")) {
            resp.header("Access-Control-Allow-Headers", requestHeader);
        }

        arg1.setResponse(resp.build());
        return arg1;

    }