角度和 CORS

2023-11-30

我正在使用 Angular 1.2 编写应用程序,并尝试在本地 glassfish 3.1 上调用 REST API。 我打电话的权利是:

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

    });
});

但我的 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. 

我将这段代码添加到我的应用程序配置中,但这没有帮助:

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

我不知道该怎么办。我会感谢每一个提示。

编辑。 我将 headers_module 添加到我的 apache wamp 中。我将以下内容添加到我的 httpd.conf 文件中:

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

但还是不行。有什么建议么??

编辑2。 好吧,我解决了。我已将此过滤器添加到我的 Spring 网络中:

 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: *在您发出请求的服务器上to(即 glassfish 服务器),而不是托管请求来源页面的服务器。

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

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

角度和 CORS 的相关文章

随机推荐