本章文档对应视频 📺 网关跨域配置
#微服务版本: 网关跨域支持
如果不知道什么是跨域(CORS),建议先阅读以下内容 跨域资源共享 CORS 详解 (opens new window)HTTP 访问控制(CORS)(opens new window)
#1. 图形化开启跨域
v5.6 后版本支持,通过路由管理模块开启指定服务的跨域访问

#2. 配置文件开启跨域
nacos pigx-gateway-dev.yml 增加如下配置
spring:
cloud:
gateway:
globalcors:
corsConfigurations:
"[/**]":
allowedOriginPatterns: "*"
allowed-methods: "*"
allowed-headers: "*"
allow-credentials: true
exposedHeaders: "Content-Disposition,Content-Type,Cache-Control"
以上配置可作为开发环境使用,生成环境建议你根据实际情况修改(请先理解 CORS,并参考 org.springframework.cloud.gateway.config.GlobalCorsProperties) 跨域时会产生预检请求(Pre-Flight Request),这样就会对你的服务器产生额外的网络请求。如果可以通过部署手段解决跨域,则可以关闭跨域支持,方法是把以上配置信息清理掉。
#单体项目配置跨域
单体项目配置跨域,pigx-boot/PigxBootSecurityServerConfiguration 配置如下属性

.cors(cors -> cors.configurationSource(request -> {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration corsConfiguration = new CorsConfiguration();
corsConfiguration.addAllowedOriginPattern("*");
corsConfiguration.addAllowedHeader("*");
corsConfiguration.addAllowedMethod("*");
corsConfiguration.setAllowCredentials(true);
source.registerCorsConfiguration("/**", corsConfiguration);
return corsConfiguration;
}))
...