Spring Cloud Gateway 跨域 CORS 配置方式实现

网上找了一堆文章全是说这样写无效

globalcors:
  cors-configurations:
    '[/**]':
      allowCredentials: true
      allowedOriginPatterns: "*"
      allowedMethods: "*"
      allowedHeaders: "*" 

都说要去代码里面写这样一个CorsWebFilter才能生效

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
        source.registerCorsConfiguration("/**", config);

        return new CorsWebFilter(source);
    }
}

这个确实可以用,但我们能直接配置的话不是方便很多吗?
后来我去官方文档里面找到了这样一段话

所以重点来了

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowCredentials: true
            allowedOriginPatterns: "*"
            allowedMethods: "*"
            allowedHeaders: "*"
        add-to-simple-url-handler-mapping: true

这样配置就可以生效了,简单吗?

我的版本是spring cloud gateway 3.0.0

如果对您有帮助,请帮忙点赞分享评论,谢谢

posted @ 2021-01-06 10:12  星临人间  阅读(8876)  评论(0编辑  收藏  举报