springboot配置跨域
一、使用注解
待补充
二、在WebMvcConfigurationSupport中统一配置
这里说下我这里将配置的跨域放在了 applcation配置文件中
2.1 springboot 2.4之前
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
@Bean public CorsFilter corsFilter() { String[] cors; if (globalProperties.getCors() == null || "".equals(globalProperties.getCors())){ cors = new String[]{"*"}; }else { cors = StrSpliter.splitToArray(globalProperties.getCors(), ',', 0, true, true); } UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.setAllowedOrigins(Arrays.asList(cors)); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
|
2.2 springboot 2.4 和 之后
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
@Bean public CorsFilter corsFilter() { final String allCorsStr = "*"; String[] cors; boolean isAll = false; String corsStr = myGlobalConfigProperties.getCors(); if (corsStr == null || "".equals(corsStr) || allCorsStr.equals(corsStr)){ cors = new String[]{"*"}; isAll = true; }else { cors = StrSpliter.splitToArray(myGlobalConfigProperties.getCors(), ',', 0, true, true); } UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); if (isAll){ config.setAllowedOriginPatterns(Arrays.asList(cors)); }else { config.setAllowedOrigins(Arrays.asList(cors)); } config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
|