FastAPI+Nginx跨域问题:Content-Type请求头不被允许
解决CORS请求头字段不被允许的问题
一、修正FastAPI的CORS配置
FastAPI的CORSMiddleware默认不会自动包含自定义请求头,得明确指定允许的字段。直接修改你的FastAPI代码:
from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware app = FastAPI() # 允许的前端域名 origins = [ "http://127.0.0.1:5500", ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], # 允许所有请求方法,也可以按需指定GET、POST等 allow_headers=["auth", "Content-Type", "Authorization"], # 把前端带的头全列在这 )
注意:allow_headers必须包含前端实际发送的所有自定义头,一个都不能漏。
二、调整Nginx的CORS配置
Nginx作为反向代理时,要确保返回的CORS头和FastAPI配置一致,同时正确处理浏览器的预检OPTIONS请求。在你的Nginx server块里更新配置:
location / { # 代理到FastAPI服务的地址 proxy_pass http://你的FastAPI服务地址:端口; # 处理OPTIONS预检请求 if ($request_method = OPTIONS) { add_header Access-Control-Allow-Origin "http://127.0.0.1:5500"; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS"; add_header Access-Control-Allow-Headers "auth, Content-Type, Authorization"; add_header Access-Control-Allow-Credentials "true"; add_header Content-Length 0; add_header Content-Type text/plain; return 204; } # 给所有请求添加CORS头,always确保错误响应也能带上 add_header Access-Control-Allow-Origin "http://127.0.0.1:5500" always; add_header Access-Control-Allow-Methods "GET, POST, OPTIONS" always; add_header Access-Control-Allow-Headers "auth, Content-Type, Authorization" always; add_header Access-Control-Allow-Credentials "true" always; }
修改后重启Nginx生效:sudo systemctl restart nginx
三、前端请求的小检查
- 虽然是GET请求,但手动加了Content-Type头会触发浏览器预检请求,必须确保后端能正确响应OPTIONS请求
- 核对前端请求的头名称和后端配置的完全一致,大小写也不能错(比如别把
auth写成Auth)
内容的提问来源于stack exchange,提问作者Hame
相关产品推荐
相关产品推荐

