Angular and CORS

为君一笑 提交于 2019-12-20 03:40:27

问题


I am writting app with angular 1.2 and I am trying to call to REST API on local glassfish 3.1. I am calling right that:

app.factory("shopModel", function($resource){
return $resource('http://localhost:8080/Schedule-service/shops', {}, {
    query: 
    {method:'GET', 
        headers: {'Content-Type': 'application/json'} 
        params:{}}

    });
});

But I get an error in my chrome.

XMLHttpRequest cannot load http://localhost:8080/Schedule-service/shops. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access. 

I added to my app config this code but this haven't helped:

app.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

I don't know what to do. I will by thankful for every tip.

Edit. I added headers_module to my apache wamp. And I added to my httpd.conf file this:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
</IfModule>

But still don't work. Any suggestions??

Edit2. Ok I resolve It. I've added this filter to my Spring web:

 public class CorsFilter extends OncePerRequestFilter {

 @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods",
            "GET, POST, PUT, DELETE, OPTIONS");
    response.addHeader("Access-Control-Allow-Headers",
            "origin, content-type, accept, x-requested-with, sid, mycustom, smuser");
        filterChain.doFilter(request, response);
    }
}

Thanks Quentin.


回答1:


You need to specify Access-Control-Allow-Origin: * on the server you are making the request to (i.e. the glassfish server), not the server hosting the page the request is coming from.

For Alice to access Bob's server, Bob has to grant permission. It would defeat the purpose if Alice could do it.




回答2:


deploy your html file to the server you are running or set header Access-Control-Allow-Origin "http://localhost" to your web server configuration.



来源:https://stackoverflow.com/questions/20583814/angular-and-cors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!