Angular JS,Jetty CORS问题

时间:2014-06-19 00:06:11

标签: angularjs jersey cors

我一直在讨论这个问题。我试图在Angular App和Jersey服务器之间启用CORS。基本上我已经为球衣实现了一个过滤器,它应允许对服务器进行角度访问:

public class SimpleCORSFilter implements ContainerResponseFilter {
/**
 * Add the cross domain data to the output if needed
 * 
 * @param creq The container request (input)
 * @param cres The container request (output)
 * @return The output request with cross domain if needed
 */
@Override
public ContainerResponse filter(ContainerRequest creq, ContainerResponse cres) {
    cres.getHttpHeaders().add("Access-Control-Allow-Origin", "*");
    cres.getHttpHeaders().add("Access-Control-Allow-Headers", "origin, content-type, accept, authorization");
    cres.getHttpHeaders().add("Access-Control-Allow-Credentials", "true");
    cres.getHttpHeaders().add("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS, HEAD");
    cres.getHttpHeaders().add("Access-Control-Max-Age", "1209600");
    return cres;
}
}

然后我将其作为init param添加到我的web.xml中。

<init-param>
<param-name>com.sun.jersey.spi.container.ContainerResponseFilters</param-name>
<param-value>com.complaints.security.SimpleCORSFilter</param-value>
</init-param>

当我点击URL - mysite:8080 / ComplaintService / service / user / authenticate from postman,其中包含一条包含用户详细信息的帖子,它返回正常(正如邮递员所期望的那样),并且标题包含所有正确的CORS相关标题。当我因为某些原因尝试从angular进行调用时,没有返回任何CORS头并且它失败了。即使我只是从浏览器中将URL作为GET命中,也会返回CORS标头。这是我的角度呼叫:

$http.post('http://mysite:8080/ComplaintService/service/user/authenticate', user).then(function(data) {
        alert(JSON.stringify(data));
    });

基本上我只是想知道我错过了一些简单的东西吗?或者它可能与弹簧安全过滤器有关?我当时认为可能会阻止应用程序到达泽西过滤器。这是弹簧过滤器:

<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

Angular目前部署在jersey上 - mysite:8081,服务器部署在mysite:8080上。任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

我使用库克服了这个问题 - com.thetransactioncompany:cors-filter:1.3.2并在我的web.xml中添加了一些配置。

<filter>
    <filter-name>CORS</filter-name>
    <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
    <init-param>
        <param-name>cors.allowOrigin</param-name>
        <param-value>*</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedHeaders</param-name>
        <param-value>origin, content-type, accept</param-value>
    </init-param>
    <init-param>
        <param-name>cors.allowGenericHttpRequests</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>cors.supportedMethods</param-name>
        <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
    </init-param>
</filter>
<filter-mapping>
    <filter-name>CORS</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

我认为问题是因为首先调用了spring安全过滤器,这似乎解决了这个问题。