Spring Cloud Gateway转发请求Angular前端报CORS错误如何解决?
问题原因
浏览器发起跨域复杂请求时会先发送OPTIONS预检请求,Spring Cloud Gateway属于WebFlux技术栈,默认不会把预检请求转发到下游服务,而是会在网关层直接处理该请求,所以你在下游MailService配置的@CrossOrigin注解不会生效,必须在网关层统一配置CORS规则。
解决方法
提供两种配置方式,任选其一即可:
方式1:代码配置CorsWebFilter
在网关服务的配置类(比如启动类GatewayServiceApplication)中添加以下Bean:
import org.springframework.context.annotation.Bean; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import java.util.Arrays; @Bean public CorsWebFilter corsWebFilter() { CorsConfiguration config = new CorsConfiguration(); // 允许的源,生产环境请替换为前端实际域名 config.addAllowedOriginPattern("*"); // 允许的请求方法 config.setAllowedMethods(Arrays.asList("POST", "OPTIONS")); // 允许的请求头 config.addAllowedHeader("*"); // 是否允许携带凭证(如Cookie),如果不需要可以设为false config.setAllowCredentials(true); // 预检请求的缓存时间,单位秒,减少重复预检请求 config.setMaxAge(3600L); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对所有路径生效 source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); }
方式2:application.yml配置(更推荐)
在网关服务的application.yml(或application.properties)中添加以下全局CORS配置:
spring: cloud: gateway: globalcors: # 允许预检请求被网关处理 add-to-simple-url-handler-mapping: true cors-configurations: '[/**]': # 允许的源,生产环境替换为实际前端地址 allowedOriginPatterns: "*" allowedMethods: - POST - OPTIONS allowedHeaders: "*" allowCredentials: true maxAge: 3600
注意事项
- 配置完成后可以删除下游MailService中
@CrossOrigin注解,避免两层都配置导致跨域响应头重复,引发浏览器报错。 - 如果生产环境需要严格控制跨域来源,请将
allowedOriginPatterns的值替换为前端的实际访问地址,比如http://your-frontend-domain.com,不要使用通配符*。 - 确认前端
environment.apiUrl拼接后路径正确:如果网关端口是8000,apiUrl应为http://网关地址:8000/api,拼接后完整请求地址为http://网关地址:8000/api/mail/feedback,和路由规则匹配。
内容的提问来源于stack exchange,提问作者Razor
相关产品推荐
相关产品推荐

