DEBUG.WIKI
PanstarCloud:部署应用,接入 AI,云服务器与 AI 网关
晚安云;香港 CN2 ¥15/月
V.PS:让项目靠近用户,亚太、欧洲、北美 KVM VPS

解决 Emissary-ingress 报错 gRPC-Web request blocked: missing CORS headers 跨域拦截修复

排查 浏览器端使用 gRPC-Web 调用 Emissary 网关报 Response to preflight request doesn't pass access control check,分析 gRPC 特有请求头放行。

问题现象

浏览器前端通过 gRPC-Web 库调用后端服务时,控制台红色报错:

Access to XMLHttpRequest at 'https://api.mycorp.com/OrderService/GetOrder' from origin 'https://app.mycorp.com' has been blocked by CORS policy: Request header field x-grpc-web is not allowed by Access-Control-Allow-Headers in preflight response.

触发根因

  1. gRPC-Web 通信依赖一套浏览器非标准的自定义 HTTP 头部(如 x-grpc-web、x-user-agent、grpc-timeout);
  2. Emissary 默认的 CORS 中间件只放通了标准的常用头部,未将 gRPC-Web 必需的协议头加入 allow_headers 白名单;
  3. 预检请求(Preflight OPTIONS)被安全策略拦截。

解决步骤

在 Emissary Mapping 资源中完整放通 gRPC-Web 必需头部与暴露头

配置专用 CORS 策略:

apiVersion: getambassador.io/v3alpha1
kind: Mapping
metadata:
  name: grpc-web-mapping
spec:
  prefix: /OrderService/
  service: order-grpc-svc:9090
  grpc: true
  cors:
    origins:
      - "https://app.mycorp.com"
    methods:
      - POST
      - OPTIONS
    headers:
      - keep-alive
      - user-agent
      - cache-control
      - content-type
      - content-transfer-encoding
      - x-accept-content-transfer-encoding
      - x-accept-response-streaming
      - x-user-agent
      - x-grpc-web
      - grpc-timeout
    exposed_headers:
      - grpc-status
      - grpc-message

验证确认

重新提交流水线更新映射:

OPTIONS 预检秒级返回放通响应,gRPC-Web 协议流式数据在浏览器与服务端之间顺畅通行。