Loading

SpringCloudGateway2.2.9跨域问题解决

1. 先贴版本


<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.12.RELEASE</version>
</parent>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-dependencies</artifactId>
   <version>Hoxton.SR12</version>
   <type>pom</type>
   <scope>import</scope>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

2. 我尝试过得方案

    @Bean
    public CorsFilter corsFilter() {
         UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
         CorsConfiguration config = new CorsConfiguration();
        config.setAllowedMethods(Stream.of(HttpMethod.GET, HttpMethod.HEAD, HttpMethod.POST, HttpMethod.OPTIONS)
                .map(Enum::name).collect(Collectors.toList()));
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("*");
        config.setMaxAge(7 * 24 * 60 * 60L); // 设置跨域check缓存时间
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }

3. 以上方案一直无效,最终解决方案

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
           '[/**]':
              allowedOrigins: "*"
              allowedMethods: "*"
              allowCredentials: true
              allowedHeaders: "*"
posted @ 2021-12-31 15:30  繁夏  阅读(434)  评论(0)    收藏  举报