整合Spring Cloud Alibaba与Gateway实现跨域的解决方案
整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发
架构图描述
-
架构层级
- 客户端 → Spring Cloud Gateway → 微服务集群(Nacos注册中心)
- Gateway作为统一入口,处理跨域请求并路由到下游服务。
-
关键组件
- 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;
}
}
验证跨域
- 前端发起请求时,检查响应头是否包含:
Access-Control-Allow-Origin: * - 预检请求(OPTIONS)应返回204状态码。
整合Spring Cloud Alibaba与Gateway实现跨域的解决方案全栈开发
注意事项
- 生产环境应限制
allowed-origins为具体域名,避免使用通配符。 - 若微服务本身也配置了CORS,需关闭以避免冲突。
- 网关层统一处理跨域后,微服务无需再添加
@CrossOrigin注解。