Angular通过Ingress访问Spring Boot后端报CORS跨域错误如何解决
问题修复方案
1. 修正Ingress配置
你的nginx.ingress.kubernetes.io/rewrite-target: /注解会把所有匹配到的路径重写为根路径,当访问Ingress的/hello路径时,转发到Spring Boot服务的路径会变成/,和后端定义的/hello接口不匹配,直接返回404,自然也不会携带CORS头。
同时CORS配置存在两处不符合规范的问题:
- 同时配置了
cors-allow-origin: "*"和cors-allow-credentials: "true",W3C规范明确要求开启凭证传输时不允许使用通配符*作为允许的源 - 额外的
configuration-snippet设置的CORS头和官方CORS注解配置冲突,会导致重复头或者配置不生效
修改后的Ingress配置如下:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: api-call-app annotations: # 如果不需要为后端服务加统一路径前缀,可直接删除rewrite-target注解 nginx.ingress.kubernetes.io/rewrite-target: /$2 nginx.ingress.kubernetes.io/enable-cors: "true" nginx.ingress.kubernetes.io/cors-allow-origin: "http://localhost" nginx.ingress.kubernetes.io/cors-allow-methods: "PUT, GET, POST, OPTIONS, DELETE" nginx.ingress.kubernetes.io/cors-allow-credentials: "true" nginx.ingress.kubernetes.io/cors-allow-headers: "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,X-CSRFToken" spec: rules: - host: localhost http: paths: - path: / pathType: Prefix backend: service: name: angular-service port: number: 80 - path: /hello(/|$)(.*) pathType: Prefix backend: service: name: springboot-service port: number: 8000
2. 移除重复CORS配置
你已经在Ingress层配置了CORS规则,不需要再在Spring Boot代码中加@CrossOrigin注解,两层CORS配置会导致浏览器识别到重复的Access-Control-Allow-Origin头,直接拦截请求。
修改后的Spring Boot代码:
@RestController public class HelloController { @GetMapping(value= "/hello", produces="text/plain") public String hello() { return "hello"; } // ... }
3. 修正前端请求目标
从报错信息来看,你的Angular代码实际请求的是http://localhost:8000/hello而非走Ingress的http://localhost/hello,请检查两处配置:
- Angular的环境配置文件中是否硬编码了后端接口的端口为8000,改为直接使用相对路径即可
- 确认代码中没有修改HttpClient的baseUrl为带8000端口的地址
验证方式:打开浏览器控制台的网络面板,查看请求的Request URL是否为http://localhost/hello,符合该格式即为正常。
内容的提问来源于stack exchange,提问作者Srishti Gupta
相关产品推荐
相关产品推荐

