You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Traefik K8s环境下跨域请求失败:如何修改Ingress配置解决?

解决跨域请求问题的Traefik配置修改

1. 创建CORS中间件

在dev命名空间下新增Traefik CORS中间件,允许来自web.all.com的跨域请求:

apiVersion: traefik.containo.us/v1alpha1
kind: Middleware
metadata:
  name: api-cors
  namespace: dev
spec:
  headers:
    accessControlAllowOriginList:
      - "https://web.all.com"
    accessControlAllowMethods:
      - "GET"
      - "POST"
      - "PUT"
      - "DELETE"
      - "OPTIONS"
    accessControlAllowHeaders:
      - "Content-Type"
      - "Authorization"
    accessControlAllowCredentials: true
    accessControlMaxAge: 86400

说明:可根据实际业务需求调整允许的HTTP方法、请求头部字段;若你的请求需要携带Cookie等凭证,需保留accessControlAllowCredentials: true。

2. 修改API的IngressRoute,关联CORS中间件

更新现有的api IngressRoute,在路由规则中添加上述CORS中间件:

apiVersion: traefik.containo.us/v1alpha1
kind: IngressRoute
metadata:
  name: api
  namespace: dev
spec:
  entryPoints:
  - websecure
  routes:
  - kind: Rule
    match: Host(`api.all.com`)
    middlewares:
    - name: api-cors  # 添加此配置关联CORS中间件
    services:
    - name: api
      namespace: dev
      port: 8000
  tls:
    secretName: dev-api-secret

原理说明

web.all.com与api.all.com属于不同域名,浏览器的同源策略会阻止跨域请求。通过在Traefik的API路由上配置CORS中间件,让API服务返回符合浏览器要求的跨域响应头,即可解除该限制。

内容的提问来源于stack exchange,提问作者user1452759

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 20:12:25