springcloud网关跨域配置
yml配置文件配置
SpringBoot 2.3.2.RELEASE
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOrigins: # 允许哪些网站的跨域请求
- "*"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
SpringBoot 2.4以上
allowedOrigins 这个要换成 allowedOriginPatterns
spring:
cloud:
gateway:
globalcors: # 全局的跨域处理
add-to-simple-url-handler-mapping: true # 解决options请求被拦截问题
corsConfigurations:
'[/**]':
allowedOriginPatterns: # 允许哪些网站的跨域请求
- "*"
allowedMethods: # 允许的跨域ajax的请求方式
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # 允许在请求中携带的头信息
allowCredentials: true # 是否允许携带cookie
maxAge: 360000 # 这次跨域检测的有效期
全局配置类实现
CorsConfig类
package com.gw.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.util.pattern.PathPatternParser;
@Configuration
public class CorsConfig {
@Bean
public CorsWebFilter corsWebFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource (new PathPatternParser());
CorsConfiguration corsConfig = new CorsConfiguration();
// 允许所有请求方法
corsConfig.addAllowedMethod ("*");
// 允许所有域,当请求头
corsConfig.addAllowedOrigin ("*");
// 允许全部请求头
corsConfig.addAllowedHeader ("*");
// 允许携带 Cookie 等用户凭证
corsConfig.setAllowCredentials (true);
// 允许全部请求路径
source.registerCorsConfiguration ("/**", corsConfig);
return new CorsWebFilter (source);
}
}