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整合Junit4
spring
那个松鼠很眼熟w4 小时前
4.Spring-Ai入门案例
java·人工智能·spring
抠脚小弟8 小时前
Spring Cache 使用详解:从入门到实战
java·spring
夏天拐跑了西瓜11 小时前
Spring Cloud 微服务实战(八):Hystrix熔断降级——从服务雪崩到断路器模式
spring cloud·hystrix·微服务
Casbin开源社区12 小时前
一个面板管住 29 个 AI 编程 Agent:Casbin Gateway 的配置统一、协议互转、用量统计与权限管控
人工智能·golang·开源·gateway·casbin
计算机学姐16 小时前
基于SpringBoot的高校爱心慈善管理系统
java·vue.js·spring boot·后端·spring·tomcat·mybatis
都叫我大帅哥17 小时前
Apache Tika 4.0 正式发布:RAG 时代文件解析的终极答案
java·spring boot·spring
霸道流氓气质1 天前
Spring AI 输出解析器进阶
人工智能·windows·spring
leonkay1 天前
C# 锁机制——【2】深入原理
开发语言·后端·spring·c#·个人开发
Raas1001 天前
AI网关和大模型网关区别?MAI Gateway(魔芋企业级AI网关)如何实现AI流量统一治理
大数据·人工智能·gateway·ai网关·mai gateway·企业级产品