Spring Gateway 跨域设置
参考这篇文章解决:https://cloud.tencent.com/developer/article/1415079
在springcloud gateway
用在微服务里面的时候,在开发环境里面因为要不同的端口对应不同的服务,可能会有因为端口问题造成的跨域问题,那么要通过在网关里设置跨域,因为springcloud gateway
用的是webflux
,所以要在webflux
层设置过滤器。 代码如下:
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;
}
}