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: "*"

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

相关推荐
源码获取_wx:Fegn089517 小时前
基于springboot + vue健身房管理系统
java·开发语言·前端·vue.js·spring boot·后端·spring
Mr1ght18 小时前
为什么 InheritableThreadLocal 在 Spring 线程池中“偶尔”能传递变量?——一次线程池上下文传播的误解
java·spring
摇滚侠18 小时前
面试实战 问题三十三 Spring 事务常用注解
数据库·spring·面试
2501_9167665418 小时前
【Spring框架】SpringJDBC
java·后端·spring
谷哥的小弟18 小时前
Spring Framework源码解析——ApplicationContextInitializer
java·spring·源码
黄俊懿19 小时前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——@GlobalTransactional注解与@globalLock生效的原理
java·spring cloud·微服务·云原生·架构·系统架构·架构师
黄俊懿20 小时前
【深入理解SpringCloud微服务】Seata(AT模式)源码解析——开启全局事务
java·数据库·spring·spring cloud·微服务·架构·架构师
Dwzun1 天前
基于SpringBoot+Vue的二手书籍交易平台系统【附源码+文档+部署视频+讲解)
java·vue.js·spring boot·后端·spring·计算机毕业设计
雨中飘荡的记忆1 天前
Spring状态机深度解析
java·后端·spring
SadSunset1 天前
(16)Bean的实例化
java·数据库·笔记·spring