Spring 4.2.2 CORS支持不起作用

时间:2015-11-03 10:48:44

标签: spring

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
}

我按照https://spring.io/blog/2015/06/08/cors-support-in-spring-framework中的指南进行操作,并将上述代码添加到我的WebConfig

但是,CORS无法正常工作,日志显示

20151103 183823 [http-bio-8080-exec-3] WARN  org.springframework.web.servlet.DispatcherServlet (DispatcherServlet.java:1136) - No mapping found for HTTP request with URI [/my/url] in DispatcherServlet with name 'dispatcher'

我可以在没有CORS(相同域名)的情况下成功调用我的api,因此它不是api问题。

在Chrome控制台中,记录显示

XMLHttpRequest cannot load http://localhost:8080/my/url. 
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.       
Origin 'http://localhost:8100' is therefore not allowed access. The response had HTTP status code 404.

1 个答案:

答案 0 :(得分:3)

只需在包含其他配置的包中添加此CROS过滤器

@Component
    public class RequestFilter implements Filter {

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

        public void init(FilterConfig filterConfig) {
        }

        public void destroy() {
        }

    }

它适用于你。