前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SpringBoot2.2.x版本添加CORS跨域访问支持

SpringBoot2.2.x版本添加CORS跨域访问支持

作者头像
海加尔金鹰
发布2020-06-09 10:36:46
1.6K0
发布2020-06-09 10:36:46
举报

看项目代码看到一个CORS跨域访问配置类,特此了解下什么是CORS跨域,以及Springboot 2.2.x版如何支持CORS跨域请求!!!

什么是CORS

CORS 全称是跨域资源共享(Cross-Origin Resource Sharing),是一种 AJAX 跨域请求资源的方式,支持现代浏览器,IE支持10以上。 详见:什么是CORS

Springboot开启CORS跨域访问支持

第一种方式:

代码语言:javascript
复制
@Configuration
public class CorsFilterConfiguration {
    @Bean
    public FilterRegistrationBean corsFilter() {
        System.out.println(123456);
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);

        // 可以设置部分地址可以进行访问
        List<String> origins = Arrays.asList("http://www.hjljy.cn", "http://api.hjljy.cn");
        config.setAllowedOrigins(origins);
        // 设置所有地址的请求都可以
        config.addAllowedOrigin("*");

        // 可以设置允许部分请求头信息
//        List<String> headers = Arrays.asList("Authorization",  "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials", "Content-Type", "Access-Control-Request-Method", "Access-Control-Request-Headers");
//        config.setAllowedHeaders(headers);
        // 设置为允许所有请求头信息
        config.addAllowedHeader("*");

        // 可以设置只支持部分请求方式
//        List<String> methods =  Arrays.asList("GET","POST","HEAD","OPTIONS","PUT");
//        config.setAllowedMethods(methods);
        // 设置为支持所有请求方式
        config.addAllowedMethod("*");


        // 可以设置部分请求路径才可以进行访问
//        source.registerCorsConfiguration("/cors/**",config);
        // 设置所有的请求路径都可以访问
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
        //设置优先级为最高
        bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
        return bean;
    }
}

第二种方式:

代码语言:javascript
复制
@Configuration
public class CorsFilterConfiguration extends WebMvcConfigurationSupport {
    @Override
    protected void addCorsMappings(CorsRegistry registry) {
        System.out.println(123456);
        registry.addMapping("/**").
                allowCredentials(true)
                .allowedHeaders("*")
                .allowedMethods("*")
                .allowedOrigins("*");
        super.addCorsMappings(registry);
    }
}

标题:SpringBoot2.2.x版本添加CORS跨域访问支持 作者:海加尔金鹰 地址:https://www.hjljy.cn/articles/2020/06/04/1591258929519.html

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-06-04,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 什么是CORS
  • Springboot开启CORS跨域访问支持
    • 第一种方式:
      • 第二种方式:
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档