通过StackSaga管理服务器访问服务时遭遇CORS错误
解决Spring Cloud API网关下的CORS错误问题
你遇到的CORS错误截图如下:

以下是针对性解决方案:
1. 统一在Spring Cloud网关配置CORS
所有请求都经过网关,统一配置是最优方案,避免每个服务重复配置。创建网关的CORS配置类:
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 GatewayCorsConfig { @Bean public CorsWebFilter corsWebFilter() { CorsConfiguration config = new CorsConfiguration(); // 生产环境建议替换为具体允许的域名,比如http://your-stack-saga-domain.com config.addAllowedOriginPattern("*"); // 允许所有HTTP请求方法 config.addAllowedMethod("*"); // 允许所有请求头(包括自定义头如token) config.addAllowedHeader("*"); // 允许携带Cookie等凭证 config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); // 对网关所有路径生效 source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
2. 清理order-service的独立CORS配置
如果order-service自身配置过CORS,建议直接移除,避免和网关的CORS规则冲突,导致浏览器解析异常。
3. 验证预检请求处理
浏览器会先发送OPTIONS预检请求,上面的配置已经自动处理这类请求,确保网关不会拦截OPTIONS请求,且返回正确的CORS响应头。
4. 确认请求源配置
如果生产环境不允许*通配所有来源,需要将addAllowedOriginPattern替换为StackSaga管理服务器的实际域名/端口,比如http://localhost:8080(根据你的实际部署地址调整)。
内容的提问来源于stack exchange,提问作者Mafei
相关产品推荐
相关产品推荐

