解决 gRPC-Web 报错 CORS preflight missing allow-headers 跨域拦截修复
排查 前端浏览器使用 grpc-web 调用 Envoy 网关时,浏览器控制台抛出 Access to fetch has been blocked by CORS policy: Request header field x-grpc-web is not allowed,分析 CORS 预检请求头与 Envoy 过滤配置。
问题现象
浏览器前端通过 @grpc/grpc-web 库发起 RPC 调用时,Network 面板 OPTIONS 预检请求失败或 POST 报错:
Access to XMLHttpRequest at 'https://api.corp/user.UserService/GetUser' from origin 'https://app.corp' has been blocked by CORS policy: Request header field x-grpc-web is not allowed by Access-Control-Allow-Headers in preflight response.
触发根因
- gRPC-Web 必须使用特殊的自定义 HTTP 标头(如
x-grpc-web、x-user-agent、grpc-timeout)传递调用元数据; - 反向代理(Envoy / Nginx)配置的 CORS 过滤插件未将这些 gRPC 专属报头加入到
allow_headers白名单中; - 未放行
grpc-status与grpc-message在响应头暴露名单(expose_headers)中,导致前端无法读取业务错误码。
解决步骤
在 Envoy 路由中配置完整的 gRPC-Web 兼容 CORS 规则
编辑 Envoy 路由配置:
cors:
allow_origin_string_match:
- safe_regex:
google_re2: {}
regex: ".*"
allow_methods: "GET, PUT, DELETE, POST, OPTIONS"
allow_headers: "keep-alive,user-agent,cache-control,content-type,content-transfer-encoding,custom-header-1,x-accept-content-transfer-encoding,x-accept-response-streaming,x-user-agent,x-grpc-web,grpc-timeout"
expose_headers: "custom-header-1,grpc-status,grpc-message"
max_age: "1728000"
确保启用了 envoy.filters.http.grpc_web 核心过滤器
完成 gRPC-Web 到原生 gRPC 二进制帧的双向转换。
验证确认
重新在前端触发 RPC 调用:
OPTIONS 预检顺利返回 HTTP 200,随后数据以 application/grpc-web+proto 高速流式传输,跨域报错彻底消失。


