【问题标题】:Angular and CORS角度和 CORS
【发布时间】:2014-01-02 05:50:59
【问题描述】:

我正在使用 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);
    }
}

谢谢昆汀。

【问题讨论】:

  • 你能解释一下你是如何解决你的错误的吗?我有类似的问题尝试了 https.conf 解决方案,htaccess 解决方案但没有成功,我正在使用启用 headers_module 的 wamp 服务器。
  • 请问,我在哪里添加 CORS 过滤器类?我可以让我的应用程序类扩展它吗?

标签: angularjs rest get cors


【解决方案1】:

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

要让 Alice 访问 Bob 的服务器,Bob 必须授予权限。如果爱丽丝能做到,那将无法达到目的。

【讨论】:

  • 如果我进行 HTTP GET 比调用 REST 中的方法,我检查了调试器。但是没有任何东西返回给 JS。
  • 是的,这就是XMLHttpRequest cannot load http://localhost:8080/Schedule-service/shops. No 'Access-Control-Allow-Origin' header is present on the requested resource. 告诉你的。您必须将该标头添加到响应中。
  • 元评论:CORS实际上是保护客户端,而不是服务器。它阻止恶意脚本访问其他资源,除非这些资源特别允许从恶意脚本的域进行访问。 See here。如果 Alice 禁用客户端安全性,即使使用 AJAX,Alice 仍然可以轻松访问 Bob 的服务器!
  • 更具体地说,同源策略用于保护客户端用户和服务器所有者之间的共享信任。 CORS 是服务器声明数据不需要这种保护的一种方式。
【解决方案2】:

将您的 html 文件部署到您正在运行的服务器或将标头 Access-Control-Allow-Origin "http://localhost" 设置为您的 Web 服务器配置。

【讨论】:

猜你喜欢
  • 2017-10-09
  • 2018-05-12
  • 2021-04-27
  • 1970-01-01
  • 2021-01-26
  • 2019-09-10
  • 2015-10-27
  • 2018-02-08
  • 2020-09-03
相关资源
最近更新 更多