CORS角js + restEasy POST [英] CORS angular js + restEasy on POST

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

问题描述

我正在从我的 angular js 应用程序执行一些 POST 请求,使用 RestEasy 实施 RESTful API 。$
我需要 CORS ,所以我添加了一个带有以下代码的servlet过滤器:

I'm doing some POST requests from my angular js app to my RESTful API implemented using RestEasy.
The case is that I need CORS so I added a servlet filter with this code:

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
    HttpServletResponse response = (HttpServletResponse) res;
    response.addHeader("Access-Control-Allow-Origin", "*");
    response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
    response.addHeader("Access-Control-Max-Age", "3600");
    response.addHeader("Access-Control-Allow-Headers", "Content-Type");
    chain.doFilter(req, res);
}

但我无法弄清楚为什么它仅适用于 GET 请求而不是 POST 请求,Chrome控制台上的错误是:

But I can't figure out why it works only with GET requests and not POST requests, the error on chrome's console is:


否'访问 - Control-Allow-Origin'标头出现在请求的
资源上

No 'Access-Control-Allow-Origin' header is present on the requested resource

我的POST请求是:

$http({method: 'POST', 
       url: myUrl,
       data: $scope.data,
       headers: {'Content-Type': 'application/json'}
});  

这是我在POST时收到的回复:

This is the reponse I receive on POST:

Allow:POST, OPTIONS
Content-Length:0
Date:Thu, 03 Apr 2014 23:27:22 GMT
Server:Apache-Coyote/1.1

任何想法?谢谢!

编辑:

在IE10上测试它可以工作,但不能在chrome上运行,而且firefox都没有...任何机构都知道为什么?

Any Idea? Thanks!

Tested on IE10 and it works but doesn't work on chrome neither firefox ... any body knows why?

推荐答案

最后我来到了这个解决方法:

它与IE合作的原因是因为IE直接发送了发布而非首先要求获得许可的预检请求。

但我仍然不知道为什么过滤器无法管理 OPTIONS 请求并默认发送过滤器中未描述的标题(似乎只是对该情况的覆盖...可能是一个restEasy的事情......)

Well finally I came to this workaround:
The reason it worked with IE is because IE sends directly a POST instead of first a preflight request to ask for permission.
But I still don't know why the filter wasn't able to manage an OPTIONS request and sends by default headers that aren't described in the filter (seems like an override for that only case ... maybe a restEasy thing ...)

所以我在我的休息服务中创建了一个 OPTIONS 路径,用于重写响应并使用响应头包含响应中的标题

So I created an OPTIONS path in my rest service that rewrites the reponse and includes the headers in the response using response header


如果有人在此之前面对这个
,我仍然在寻找干净的方法。

I'm still looking for the clean way to do it if anybody faced this before.

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

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