nginx支持api跨域post需显式允许content-type等请求头并正确响应options预检:匹配options请求返回204,设置access-control-allow-origin(非*)、credentials、methods、headers(含content-type),再代理真实请求。

要让 Nginx 正确支持 API 接口的跨域 POST 请求,关键不只是加 Access-Control-Allow-Origin,还必须显式允许客户端发送的 Content-Type(尤其是 application/json、application/x-www-form-urlencoded 等),否则浏览器会在预检(OPTIONS)阶段直接拦截。
必须放行 OPTIONS 预检请求
浏览器对非简单请求(如带自定义 header、JSON body 或非 GET/POST 的 method)会先发一个 OPTIONS 请求。Nginx 必须能响应这个请求,且返回合法的 CORS 头:
- 匹配所有 OPTIONS 请求,直接返回 204(无内容),不转发给后端
- 在响应头中设置
Access-Control-Allow-Methods,包含POST, GET, OPTIONS等实际需要的方法 -
Access-Control-Allow-Headers必须包含客户端实际发送的 header,例如Content-Type, Authorization, X-Requested-With
Content-Type 要明确列入 Access-Control-Allow-Headers
如果前端用 fetch 或 axios 发送 JSON 数据(Content-Type: application/json),Nginx 的 CORS 响应头里 必须显式包含 application/json 在 Access-Control-Allow-Headers 中,否则预检失败:
add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,Content-Type,Authorization,Accept,Origin';
注意:Content-Type 是 header 名,不是值;它的值(如 application/json)不需要单独声明,但 header 名必须被允许。
避免通配符导致认证请求失败
如果接口需要携带 Cookie 或使用 withCredentials: true,就不能用 * 作为 Access-Control-Allow-Origin 的值,必须指定具体域名(如 https://example.com),同时还要加上:
add_header 'Access-Control-Allow-Credentials' 'true';-
add_header 'Access-Control-Allow-Origin' 'https://example.com';(不能是*) - 确保
Access-Control-Allow-Headers不含通配符,全部显式列出
完整 minimal 示例(适用于 /api/ 路由)
以下是一个可直接嵌入 location 块的轻量配置:
location ^~ /api/ {<br> # 处理预检<br> if ($request_method = 'OPTIONS') {<br> add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com';<br> add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';<br> add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,Content-Type,Authorization,Accept,Origin';<br> add_header 'Access-Control-Allow-Credentials' 'true';<br> add_header 'Access-Control-Max-Age' 1728000;<br> add_header 'Content-Type' 'text/plain; charset=utf-8';<br> add_header 'Content-Length' 0;<br> return 204;<br> }<br> # 处理真实请求<br> add_header 'Access-Control-Allow-Origin' 'https://your-frontend.com';<br> add_header 'Access-Control-Allow-Credentials' 'true';<br> add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';<br> add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,Content-Type,Authorization,Accept,Origin';<br> proxy_pass http://backend;<br>}大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











