部署在AWS EC2的Swagger UI调用多微服务遇CORS跨域问题求助
解决AWS部署后Swagger UI的CORS跨域问题
一、先修正API Docs地址配置
错误中请求的http://172.17.0.3:9998/v3/api-docs是内网IP,而Swagger UI页面部署在公网ELB域名http://svs-2.elb.amazonaws.com,外部浏览器既无法访问内网IP,也会触发跨域限制:
- 修改Swagger UI的配置,将API Docs的请求地址替换为ELB公网域名,比如
http://svs-2.elb.amazonaws.com/v3/api-docs(需确保网关已映射该路径)。 - 若使用Spring Boot,检查Swagger配置类,确保
api-docs的访问路径配置为对外暴露的公网地址,而非内网IP。
二、统一网关层面配置CORS
既然有统一网关,直接在网关层配置CORS是最优方案,无需在后端服务器单独配置:
以Spring Cloud Gateway为例
在网关的application.yml中添加全局CORS配置:
spring: cloud: gateway: globalcors: cors-configurations: '[/**]': allowed-origins: "*" # 生产环境建议指定具体域名,如http://svs-2.elb.amazonaws.com allowed-methods: [GET, POST, PUT, DELETE, OPTIONS] allowed-headers: "*" allow-credentials: true
或通过代码配置类实现:
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 CorsConfig { @Bean public CorsWebFilter corsWebFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedOrigin("*"); config.addAllowedMethod("*"); config.addAllowedHeader("*"); config.setAllowCredentials(true); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
三、后端服务器针对性配置CORS
如果服务器并非Apache,根据实际服务类型调整:
1. Nginx反向代理场景
找到Nginx配置文件(通常在/etc/nginx/nginx.conf或/etc/nginx/conf.d/下的站点配置),在server块中添加:
location / { add_header Access-Control-Allow-Origin *; add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS'; add_header Access-Control-Allow-Headers 'Content-Type, Access-Control-Allow-Headers'; if ($request_method = OPTIONS) { return 204; } }
修改后重启Nginx:sudo systemctl restart nginx
2. Spring Boot微服务单独配置
若未通过网关统一处理,可在每个微服务中添加CORS配置:
import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class WebConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS") .allowedHeaders("*") .allowCredentials(true); } }
四、AWS ELB层面补充配置
如果使用AWS应用负载均衡(ALB),可直接在监听器中添加CORS规则:
- 登录AWS控制台,进入EC2 -> 负载均衡器 -> 选中目标ELB -> 监听器 -> 编辑规则
- 添加新规则:当请求方法为OPTIONS时,返回以下响应头并设置状态码204:
Access-Control-Allow-Origin: *Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONSAccess-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers
内容的提问来源于stack exchange,提问作者Aditya Aryan
相关产品推荐
相关产品推荐

