SpringCloud Gataway 跨域配置
Spring Boot版本:2.3.4.RELEASE
Spring Cloud版本:Hoxton.SR8
一、通过配置文件配置跨域
spring:
cloud:
gateway:
globalcors:
cors-configurations:
'[/**]':
allow-credentials: true #允许携带cookie
allowed-origins: "*" #允许跨域的请求,设置*为全部
allowed-headers: "*" #允许跨域请求里的head字段,设置*为全部
allowed-methods: "*" #允许跨域的method, 默认为GET和OPTIONS,设置*为全部
max-age: 3600
二、通过配置类配置跨域
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;
/**
* 跨域配置
*/
@Configuration
public class MyCorsConfiguration {
@Bean
public CorsWebFilter corsWebFilter(){
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration cors = new CorsConfiguration();
//允许跨域的请求头
cors.addAllowedHeader("*");
//允许请求的方法
cors.addAllowedMethod("*");
//允许哪些请求源跨域
cors.addAllowedOrigin("http://localhost");
//是否携带cookie
cors.setAllowCredentials(true);
//允许跨域的路径
source.registerCorsConfiguration("/**",cors);
return new CorsWebFilter(source);
}
}
配置其中一种即可