在springcloud gateway
用在微服务里面的时候,在开发环境里面由于要不一样的端口对应不一样的服务,可能会有由于端口问题形成的跨域问题,那么要经过在网关里设置跨域,由于springcloud gateway
用的是webflux
,因此要在webflux
层设置过滤器。 代码以下:java
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter(){ UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", buildConfig()); return new CorsWebFilter(source); } private CorsConfiguration buildConfig(){ CorsConfiguration corsConfiguration = new CorsConfiguration(); //在生产环境上最好指定域名,以避免产生跨域安全问题 corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } }