springCloud 网关(gateway)配置跨域访问

如果项目是分布式架构,通过网关进行路由转发的,那么项目中如果存在跨域的访问,在每一个项目中单独配置,显示是错误的,我们只需要在网关处进行处理,其它项目都是由网关进行转发的,他们是不会存在跨域访问的(具体为啥,可以查询跨域产生的原因)

下面就上代码了

java 复制代码
package org.example.sysgateway.filter;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;

@Configuration
public class CorsConfig {
    @Bean
    public CorsWebFilter corsWebFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOriginPattern("*");
        config.addAllowedMethod("*");
        config.addAllowedHeader("*");
        config.setAllowCredentials(true);
        config.setMaxAge(3600L);

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

        return new CorsWebFilter(source);
    }
}

将这个文件复制到网关中即可,当然,也可以在网关的配置文件中进行编写,

java 复制代码
spring:
  cloud:
    gateway:
      globalcors:
        cors-configuration:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"

然后这个是一个挺简单的东西,没啥好说的,写出来的目的是方便以后遇到,可以及时想起这里有一个解决方案,如有更好方法,欢迎留言

相关推荐
廋到被风吹走1 天前
【Spring】Spring Cloud 分布式事务:Seata AT/TCC/Saga 模式选型指南
分布式·spring·spring cloud
程序员小白条1 天前
面试 Java 基础八股文十问十答第八期
java·开发语言·数据库·spring·面试·职场和发展·毕设
刘一说1 天前
Spring Cloud微服务中的分布式追踪:从故障定位到性能优化的革命性实践
分布式·spring cloud·微服务
问今域中1 天前
Spring Security + JWT
java·后端·spring
Full Stack Developme1 天前
Redis 实现主从同步
java·redis·spring
musenh1 天前
spring学习1
java·学习·spring
白典典2 天前
解决iTextPDF生成手册时目录页码与实际页码不匹配问题
java·spring·intellij-idea
xiaolyuh1232 天前
Redis 核心业务流程
java·redis·spring
计算机程序设计小李同学2 天前
平价药店销售与管理系统
java·mysql·spring·spring cloud·ssm
廋到被风吹走2 天前
【Spring】Spring Cloud 链路追踪:SkyWalking/Pinpoint 字节码增强与 TraceId 传递机制
spring·spring cloud·skywalking