CORS 头部被拒 — Allow-Headers

'Request header field x-auth-token is not allowed' 的原因与 Allow-Headers 配置,模拟器演示。

场景预设

请求 — 浏览器(页面)侧

Method

Content-Type

自定义头部

Access-Control-Request-Headers: content-type, x-auth-token

响应 — 服务器返回的头部

Access-Control-Allow-Origin

Access-Control-Allow-Methods

Access-Control-Allow-Headers

请求所需 + 常用头部 — 点击切换

浏览器处理步骤

→

页面发起 fetch 请求

•

非简单请求 — 需要 OPTIONS 预检

→

发送 OPTIONS 预检请求

OPTIONS /data HTTP/1.1
Origin: https://myapp.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, x-auth-token
←

服务器预检响应到达

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://myapp.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: content-type
✓

Allow-Origin 与来源一致 — 通过

✓

请求方法在 Allow-Methods 中 — 通过

✗

请求头部不在 Allow-Headers 中x-auth-token

—

未携带凭据 — 跳过检查

✗

浏览器拦截响应并 reject fetch

浏览器控制台

✕ Access to fetch at 'https://api.example.com/data' from origin 'https://myapp.example.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

(index):1

修改任意值,下方步骤会立即重新计算。试试「credentials + *」场景看通配符为何被拦。

Authorization、X-Api-Key 等自定义头部乃至 application/json 都不在 safelist 内,会进入预检的 ACRH。Allow-Headers 没覆盖全时,以 'header field X is not allowed' 拦截。

坑不在大小写(头部名不区分大小写)而在遗漏——很多人不知道 content-type 本身也要进允许列表,只写 authorization 照样失败。 CORS 模拟器

常见问题

Authorization 也要进 Allow-Headers 吗?
要,它不在 safelist 内。JWT API 通常需要 content-type 和 authorization 两项。
Allow-Headers 能写 * 吗?
无凭据请求基本可用;凭据请求建议显式列表。

其他场景