通常来说我们都是会写一个配置类来说明,例如下面这样的:
/**
* 全局跨域配置
* 注意:前端从网关进行调用时需要配置
*/
@Configuration
public class GlobalCorsConfig {
@Bean
public CorsWebFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.addAllowedMethod("*");
config.addAllowedOriginPattern("*");
config.addAllowedHeader("*");
config.setAllowCredentials(true);
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());
source.registerCorsConfiguration("/**", config);
return new CorsWebFilter(source);
}
}
当然如果你引用的是Sa-Token这类框架,还需要在其配置类中,对预检请求做处理:
@Configuration
public class SaTokenConfig {
@Bean
public SaReactorFilter getSaReactorFilter(IgnoreUrlsConfig ignoreUrlsConfig) {
return new SaReactorFilter()
// 拦截地址
.addInclude("/**")
// 配置白名单路径
.setExcludeList(ignoreUrlsConfig.getUrls())
// 鉴权方法:每次访问进入
.setAuth(obj -> {
// 对于OPTIONS预检请求直接放行
SaRouter.match(SaHttpMethod.OPTIONS).stop();
....
}
基本上这样就ok了。
当然也可以在配置文件中来对SpringCloud进行指定,这样就省略在写配置类的过程(当然还是建议第一种写法,灵活性更高):
cloud:
gateway:
globalcors:
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
# options请求 就是一种询问服务器是否浏览器可以跨域的请求
# 如果每次跨域都有询问服务器是否浏览器可以跨域对性能也是损耗
# 可以配置本次跨域检测的有效期maxAge
# 在maxAge设置的时间范围内,不去询问,统统允许跨域
cors-configurations:
'[/**]':
allowedOriginPatterns: "*"
allowedHeaders: "*"
allowedMethods: # 允许跨域的 Ajax请求
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
# allowCredentials: true
maxAge: 3600
discovery:
locator:
enabled: true
lower-case-service-id: true
discovery.locator.enabled 设置为 true 时,Spring Cloud Gateway 会启用服务发现功能,自动根据注册到服务发现(如 Eureka、Consul 等)中的服务来生成路由规则。也就是说当你有多个微服务在注册中心中时,Spring Cloud Gateway 可以动态地识别并路由到对应的服务,而无需手动配置每个服务的路由
下面我们重点解决关于跨域的部分:
这里主要是通过配置globalcors来实现的,具体实现了:
- 允许任何来源的请求 (
allowedOriginPatterns: "*"
). - 允许所有 HTTP 方法(如 GET, POST, PUT 等)。
- 配置了最大预检请求缓存时间 maxAge 为 3600 秒,减少了跨域请求时的性能损耗。
maxAge: 3600:设置预检请求的有效期为 3600 秒(即 1 小时)。浏览器会缓存此信息,在 maxAge 时间内不再发送预检请求。