一尘不染

SpringBoot和CORS

spring-boot

我在Spring Boot时遇到了CORS的问题。我已经像这样配置了CORS

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

我想启用所有标头和其他内容。

它非常适合GET请求

 $.get("someUrl, function(data, status){
     console.log(data[0].latitude);
 });

但是每当我发出这样的POST请求时

 $.ajax({
        url: 'someUrl',
        type: 'post',
        dataType: 'json',
        crossDomain: true,
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            console.log(data);
        },
        data: object
    });

我得到以下

OPTIONS XHR  "someUrl" [HTTP/1.1 403 Forbidden 4ms]
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at  "someUrl". 
(Reason: CORS header 'Access-Control-Allow-Origin' missing).

我该如何解决这个问题?


阅读 409

收藏
2020-05-30

共1个答案

一尘不染

使用Spring Boot应用程序配置CORS过滤器的简单方法是制作@Component实现Filter如下的类:

@Component
public class SimpleCORSFilter implements Filter {

    @Override
    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, PATCH");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.setHeader("Access-Control-Expose-Headers", "Location");
        chain.doFilter(req, res);
    }

    @Override
    public void init(FilterConfig filterConfig) {}

    @Override
    public void destroy() {}

}

它与 spring-boot 1.3.0

编辑(2017年10月):

仍可与 spring-boot 1.5.8

2020-05-30