gateway网关跨域的配置

本文介绍了两种在Spring Gateway中配置跨域的方法:一种是通过Java配置类,另一种是在YML文件中设置。博主强调配置跨域时避免重复,以防出现跨域问题。文章提供了解决此类问题的具体代码示例,并分享了遇到的两重跨域错误的截图,旨在帮助开发者避免类似困扰。
摘要由CSDN通过智能技术生成

第一种方法在网关服务里增加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个小时,各种配置,各种尝试。最后在一篇文章里看到我配置了两重跨域。导致前端一直访问报跨域。

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

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

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值