Gateway网关中配置跨域的解决方案
1.配置文件:application.yml(在网关中开启跨域访问功能)
# 网关跨域配置start---------------------------------
# 开启网关的跨域功能,具体微服务上的跨域需要进行关闭,否则无效
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" # 跨域处理 允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
# 网关跨域配置end---------------------------------
配置案列:
spring:
application:
name: dabing-gateway
cloud:
gateway:
# 网关跨域配置start---------------------------------
# 开启网关的跨域功能,具体微服务上的跨域需要进行关闭,否则无效
globalcors:
cors-configurations:
'[/**]': # 匹配所有请求
allowedOrigins: "*" # 跨域处理 允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
# 网关跨域配置end---------------------------------
routes:
- id: xxx
uri: lb://xxx
predicates:
- Path=/xxx/**
filters:
- StripPrefix= 1
2.代码实现方式
@Configuration
public class CorsConfig {
// 该配置适用于reactive响应式环境
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
// springboot升级成2.4.0以上时对AllowedOrigin设置发生了改变,不能有”*“,可以替换成AllowedOriginPattern
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
// 必须是reactive包下的UrlBasedCorsConfigurationSource
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
// 该配置适用于servlet环境
@Bean
public CorsFilter corsFilter() {
//1. 添加 CORS配置信息
CorsConfiguration config = new CorsConfiguration();
//放行哪些原始域
config.addAllowedOrigin("*");
//是否发送 Cookie
config.setAllowCredentials(true);
//放行哪些请求方式
config.addAllowedMethod("*");
//放行哪些原始请求头部信息
config.addAllowedHeader("*");
//暴露哪些头部信息
config.addExposedHeader("*");
//2. 添加映射路径
UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();
corsConfigurationSource.registerCorsConfiguration("/**",config);
//3. 返回新的CorsFilter
return new CorsFilter(corsConfigurationSource);
}
重写WebMvcConfigurer接口的默认方法
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
//该值对应的是是跨域请求 Response 头中的 ‘Access-Control-Allow-Credentials’ 字段值。浏览器是否将本域名下的 cookie 信息携带至跨 域服务器中。默认携带至跨域服务器中,但要实现 cookie 共享还需要前端在 AJAX 请求中打开 withCredentials 属性。
.allowCredentials(true)
//放行哪些原始域
.allowedOrigins("*")
//设置允许的方法(post、get等)
.allowedMethods("*")
//表示允许的请求头。默认为 *,表示该域中的所有的请求都被允许。
.allowedHeaders("*")
//跨域请求请求头中允许携带的除Cache-Controller、Content-Language、Content-Type、Expires、Last-Modified、Pragma这六个基本字 段之外的其他字段信息,对应的是跨域请求 Response 头中的 'Access-control-Expose-Headers’字段值。
.exposedHeaders("*");
//跨域允许时间:maxAge(3600)表明在3600秒内,不需要再发送预检验请求,可以缓存该结果
.maxAge(3600);
}
}