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