Spring Boot 和 CORS [英] Spring Boot and CORS

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

问题描述

我在 Spring Boot 中遇到了 CORS 问题.我已经像这样配置了 CORS

I facing issue with CORS in spring boot. I have configured CORS like this

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {

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

我想这会启用所有标题和其他内容.

which I suppose enables all header and other stuff.

它非常适合 GET 请求

It works excellently with GET request

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

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

But whenever I make POST request like this

 $.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).

我该如何解决这个问题?

How can I solve this issue?

推荐答案

使用 Spring Boot 应用程序配置 CORS 过滤器的简单方法是创建实现 Filter@Component 类像这样:

Simple way of configuring CORS filter with Spring Boot app is to make @Component class which implements Filter like this:

@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

Still works with spring-boot 1.5.8

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

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