整合Spring Cloud Alibaba与Gateway实现跨域的解决方案

整合Spring Cloud Alibaba与Gateway实现跨域的解决方案

整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发

架构图描述
  1. 架构层级

    • 客户端 → Spring Cloud Gateway → 微服务集群(Nacos注册中心)
    • Gateway作为统一入口,处理跨域请求并路由到下游服务。
  2. 关键组件

    • Gateway:基于Spring Cloud Gateway,配置全局CORS规则。
    • Nacos:服务注册与发现,动态路由配置。
    • 微服务:无需单独处理跨域,由Gateway统一代理。

整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发

代码实现
1. 添加依赖(pom.xml)
xml 复制代码
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
2. 全局跨域配置(application.yml)
yaml 复制代码
spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]':
            allowed-origins: "*"  # 允许所有源(生产环境应指定具体域名)
            allowed-methods:
              - GET
              - POST
              - PUT
              - DELETE
              - OPTIONS
            allowed-headers: "*"
            allow-credentials: true  # 允许携带Cookie
            max-age: 3600  # 预检请求缓存时间

整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发

3. 动态路由配置(可选)

通过Nacos配置中心动态更新路由规则:

yaml 复制代码
spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://user-service
          predicates:
            - Path=/api/user/**
          filters:
            - StripPrefix=1
4. 启动类配置
java 复制代码
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}
高级配置(Java代码方式)

若需更灵活的控制,可通过WebFluxConfigurer自定义:

java 复制代码
@Configuration
public class CorsConfig implements WebFluxConfigurer {
    @Override
    public void addCorsMappings(ServerHttpResponse response) {
        CorsWebFilter corsFilter = new CorsWebFilter(source -> {
            CorsConfiguration config = new CorsConfiguration();
            config.addAllowedOrigin("*");
            config.addAllowedMethod("*");
            config.addAllowedHeader("*");
            return config;
        });
        return corsFilter;
    }
}
验证跨域
  1. 前端发起请求时,检查响应头是否包含:
    Access-Control-Allow-Origin: *
  2. 预检请求(OPTIONS)应返回204状态码。

整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发

注意事项
  • 生产环境应限制allowed-origins为具体域名,避免使用通配符。
  • 若微服务本身也配置了CORS,需关闭以避免冲突。
  • 网关层统一处理跨域后,微服务无需再添加@CrossOrigin注解。
相关推荐
良许Linux1 分钟前
DSP的选型和应用
后端·stm32·单片机·程序员·嵌入式
有味道的男人3 分钟前
1688获得商品类目调取商品榜单
java·前端·spring
leaves falling4 分钟前
c语言单链表
c语言·开发语言
独自破碎E7 分钟前
【中心扩展法】LCR_020_回文子串
java·开发语言
不光头强8 分钟前
spring boot项目欢迎页设置方式
java·spring boot·后端
XLYcmy9 分钟前
一个用于统计文本文件行数的Python实用工具脚本
开发语言·数据结构·windows·python·开发工具·数据处理·源代码
掘根13 分钟前
【即时通讯系统】项目框架与微服务拆分设计
微服务·云原生·架构
4311媒体网17 分钟前
自动收藏功能的实现方法
java·开发语言
xyq202419 分钟前
SQLite 创建表
开发语言