I have a problem fetching json from a remote server that I control. I have 2 web applications, one serving data and running on port 3311, the other, requesting data, is run
The answer above solved the problem.
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
When an HTML page was calling an angular controller with a service like:
$http.get(dataUrl).success(function (data) {
$scope.data.products = data;
})
.error(function (error) {
$scope.data.error = error;
});
This is probably due to the default behavior of Angular to include the request header 'X-Requested-With'
, which can cause problems with CORS. This was fixed in v 1.1.1 (the unstable branch - see v1.1.1 bug fixes) by removing the header from cross domain requests: https://github.com/angular/angular.js/issues/1004.
It's easy to remove the header and get this working on the 1.0 branch. The following line will remove the header from all requests (not only CORS) done by the $http service in your app:
yourModule
.config(function($httpProvider){
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
Update A little warning - Angular (like jQuery) doesn't support CORS for IE9. IE10 is the first IE browser that supports CORS. This blogpost describes how you can get CORS support in IE8/IE9 under certain conditions, but it won't work with the Angular $http service: http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
Requested headers has to be set at the server side. There are many ways in setting this
1.One can be
<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.Independent of the server you can develop a custom class that can be passed as init paramter to jersey servlet
com.sun.jersey.spi.container.ContainerResponseFilters
helpers.TestCorpsFilter
enter code here
`public class TestCorpsFilter implements 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;
}
web.config
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
</customHeaders>
</httpProtocol>
</system.webServer>