SpringCloud Gateway 跨域配置
配置文件
#跨域支持
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-headers[0]=*
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-methods[0]=*
spring.cloud.gateway.globalcors.cors-configurations.[/**].allowed-origins[0]=*
配置组件
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;/*** @author zhe.xiao* @version 1.0* @since 2024/8/21 下午2:59*/
@Configuration
public class CorsConfig {@Beanpublic CorsWebFilter corsFilter() {CorsConfiguration config = new CorsConfiguration();config.addAllowedMethod("*");config.addAllowedOrigin("*");config.addAllowedHeader("*");config.addExposedHeader("*");UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());source.registerCorsConfiguration("/**", config);return new CorsWebFilter(source);}
}
Springboot 服务跨域配置
配置组件
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;/*** @author zhe.xiao* @version 1.0* @since 2024/8/21 下午3:19*/
@Configuration
public class CorsConfig {@Beanpublic CorsFilter corsFilter() {//1. 添加 CORS配置信息CorsConfiguration config = new CorsConfiguration();//放行哪些原始域config.addAllowedOrigin("*");//放行哪些请求方式config.addAllowedMethod("*");//放行哪些原始请求头部信息config.addAllowedHeader("*");//暴露哪些头部信息config.addExposedHeader("*");//2. 添加映射路径UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();corsConfigurationSource.registerCorsConfiguration("/**", config);//3. 返回新的CorsFilterreturn new CorsFilter(corsConfigurationSource);}
}