角度和 CORS [英] Angular and CORS

查看:16
本文介绍了角度和 CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 angular 1.2 编写应用程序,并且我正在尝试在本地 glassfish 3.1 上调用 REST API.我说得对:

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:{}}

    });
});

但是我的 chrome 出现错误.

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.

编辑.我将 headers_module 添加到我的 apache wamp 中.我在我的 httpd.conf 文件中添加了这个:

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??

编辑2.好的,我解决了.我已将此过滤器添加到我的 Spring Web 中:

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);
    }
}

谢谢昆汀.

推荐答案

您需要在您提出请求的服务器上指定 Access-Control-Allow-Origin: * (即 glassfish 服务器),而不是托管请求来自的页面的服务器.

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.

为了让 Alice 访问 Bob 的服务器,Bob 必须授予权限.如果爱丽丝能做到,那目的就落空了.

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

这篇关于角度和 CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆