Springboot跨域和SpringCloud跨域
1、Springboot全局跨域
@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(true); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); config.addAllowedMethod("*"); source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
生成环境通常需要在配置文件里设置,而且origin一般不能用*号
application.yml文件配置
cors:
allowed-origin: http://localhost,http://192.168.1.104
读取配置
@Data @Configuration @ConfigurationProperties(prefix = "cors") public class CorsProperties { private String[] allowedOrigin = {"*"}; private String[] allowedHeader = {"*"}; private String[] allowedMethod = {"*"}; private boolean allowCredentials = true; }
注入CorsProperties 后获取
@Bean public CorsFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); CorsConfiguration config = new CorsConfiguration(); config.setAllowCredentials(corsProperties.isAllowCredentials()); for (String origin : corsProperties.getAllowedOrigin()) { config.addAllowedOrigin(origin); } for (String header : corsProperties.getAllowedHeader()) { config.addAllowedHeader(header); } for (String method : corsProperties.getAllowedMethod()) { config.addAllowedMethod(method); } source.registerCorsConfiguration("/**", config); return new CorsFilter(source); }
2、Springcloud跨域
微服务的跨域一般设置在网关(其他微服务的跨域必须去掉),配置与Springboot基本相同。
@Configuration public class CorsConfig { @Bean public CorsWebFilter corsWebFilter() { CorsConfiguration cfg = new CorsConfiguration(); cfg.setAllowCredentials(true); cfg.addAllowedOrigin("*"); cfg.addAllowedMethod("*"); cfg.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", cfg); return new CorsWebFilter(source); } }