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

Updated on with 791 views

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

什么是CORS

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

Springboot开启CORS跨域访问支持

第一种方式:

@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;
    }
}

第二种方式:


@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跨域访问支持
作者:hjljy
地址:https://www.aliuying.com/articles/2020/06/04/1591258929519.html

Responses
取消