gateway网关跨域的配置

2022-07-06 08:59:31

第一种方法在网关服务里增加config,详细代码如下。

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() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedMethod("*");
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");

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

        return new CorsWebFilter(source);
    }
}

第二种方法是在yml文件里配置

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]'
            allowCredentials: true
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"

博主亲测第一种配置可以,第二种没试,感兴趣的朋友们可以尝试一下。

另外博主特别强调,不要配置两重跨域。意思就是网关配置了跨域,其他微服务就不要配置跨域了。因为这个我搞了2个小时,各种配置,各种尝试。最后在一篇文章里看到我配置了两重跨域。导致前端一直访问报跨域。

下面看这幅图,就是两重跨域的错误。

希望我的文章能帮到,正在敲代码的你!


  • 作者:zc410166
  • 原文链接:https://blog.csdn.net/zc410166/article/details/118176223
    更新时间:2022-07-06 08:59:31