FastAPI配置CORS Headers后本地测试不生效求助
我已按照FastAPI官方文档配置CORS Headers,但本地测试接口时,CORS Headers并未出现。使用Postman测试时,在Headers标签页无法观察到相关头信息,代码实现如下:
from dotenv import load_dotenv from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware import requests from fastapi import Response import os load_dotenv() key = os.environ["DRF_API_KEY"] app = FastAPI() origins = [ "http://localhost.tiangolo.com", "https://localhost.tiangolo.com", "http://localhost:8000", "http://localhost:8080", "http://localhost:8080", "http://127.0.0.1:8000" ] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) @app.get("/{email}") async def root(email): print("hiya") # print("Email is ", email) # print("Key is ", key) r = requests.get(f'https://api.mydomain.io/retrieve_artist_user/{email}', headers={'Authorization': f'Api-Key {key}'}) text = r.text print(text) return Response(content=text, media_type="application/json")
Postman需手动添加Origin请求头
CORS响应头仅在服务器检测到跨域请求(即带有Origin请求头的请求)时才会返回。Postman默认不会自动携带Origin头,你需要在Postman的请求头中手动添加Origin字段,值设置为你origins列表中的任意一个地址(比如http://localhost:8080),重新发送请求后就能看到CORS相关响应头。确认中间件加载顺序
确保CORSMiddleware是第一个被添加的中间件,你的代码当前顺序正确,但如果后续新增其他中间件,要保证add_middleware(CORSMiddleware...)的调用在所有路由定义和其他中间件之前,避免被其他中间件拦截处理。验证请求Origin是否在允许列表内
检查测试时使用的Origin值是否完全匹配origins列表中的条目(包括协议、域名、端口),如果不在列表内,服务器不会返回CORS响应头。另外你的origins列表中有重复的http://localhost:8080,可以删除重复项,不影响功能但更整洁。用浏览器测试真实跨域场景
编写简单的HTML页面,通过fetch或axios调用你的FastAPI接口,打开浏览器开发者工具的网络面板查看请求的响应头,这是最贴近实际业务场景的测试方式,能直接验证CORS配置是否生效。
内容的提问来源于stack exchange,提问作者Christopher

