fastapi: 配置接口允许CORS跨域访问

一,代码:

# 创建FastAPI应用,并传入 lifespan
api_app = FastAPI(title="我的API项目",# docs_url=None,docs_url=None,redoc_url=None,openapi_url=None,root_path="/api",)# 1. 定义允许访问的源(Origins)列表
# 这些是你允许访问后端接口的前端项目的地址
origins = ["http://127.0.0.1:8008",      # 我本地的测试地址"http://localhost:5173",      # Vite/Vue/React 常见的本地开发地址"http://127.0.0.1:5173","https://www.yourdomain.com", # 生产环境的域名
]# 2. 将 CORSMiddleware 添加到应用中
api_app.add_middleware(CORSMiddleware,allow_origins=origins,           # 允许跨域的源列表allow_credentials=True,          # 是否允许携带 Cookieallow_methods=["*"],             # 允许的请求方法,"*" 表示所有(GET, POST, PUT, DELETE 等)allow_headers=["*"],             # 允许的请求头,"*" 表示所有(如 Content-Type, Authorization 等)
)

 

二,测试效果:

未允许访问前:

image

允许访问后:

image