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

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

相关推荐
无心水5 小时前
【全域智能营销实战】2、Spring AI 模块化架构深度解读:从 1.0 到 2.0 的演进与最佳实践
人工智能·spring·架构·harness·顶尖架构师·全域智能营销·harmess
livemetee10 小时前
【关于Spring声明式事务】
java·后端·spring
Esaka_Forever12 小时前
Python 完整内存管理机制详解
开发语言·python·spring
殳翰13 小时前
spring对junit的支持
spring·junit·sqlserver
Devin~Y13 小时前
抖音级短视频推荐与直播带货平台面试实战:从 Java 微服务到 RAG 智能客服全链路解析
java·spring boot·redis·spring cloud·kafka·agent·rag
happyprince14 小时前
09-vLLM KV Cache 系统完整分析
java·spring·vllm
AI人工智能+电脑小能手15 小时前
【大白话说Java面试题 第154题】【06_Spring篇】第14题:Spring 支持的 Bean 作用域
java·开发语言·spring·面试
河阿里16 小时前
SLF4J深度指南(Java):从原理到 Spring 项目实战
java·开发语言·spring
Ricky_Theseus16 小时前
CrewAI 生产化:缓存、回调、LLM 配置
java·spring·缓存
TanYYF1 天前
spring ai入门教程二
java·人工智能·spring