You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

FastAPI Swagger页面加载失败求助:跨域及openapi.json获取问题

解决FastAPI Swagger文档跨域加载失败问题

问题原因

你启动Uvicorn时用了--host 0.0.0.0,服务器会监听所有网络接口,但访问Swagger文档时用的是http://127.0.0.1:8000,导致Swagger UI默认以0.0.0.0:8000请求openapi.json,页面地址和请求地址的Origin不匹配,触发跨域错误。

解决方案

方案1:直接用0.0.0.0访问文档

访问Swagger文档时,使用http://0.0.0.0:8000/docs代替http://127.0.0.1:8000/docs,页面Origin和请求地址一致后,即可正常加载文档。

方案2:指定FastAPI的服务器地址

在FastAPI应用代码中,给FastAPI实例添加servers参数,明确指定Swagger UI使用的请求地址:

from fastapi import FastAPI

app = FastAPI(
    servers=[
        {"url": "http://127.0.0.1:8000", "description": "本地开发服务器"}
    ]
)

@app.get("/")
async def root():
    return {"message": "Hello"}

修改后重启服务,再访问http://127.0.0.1:8000/docs即可正常加载。

方案3:配置CORS中间件(兜底方案)

如果前两种方法不适用,可以添加CORS中间件解除跨域限制:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 生产环境建议替换为具体域名
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "Hello"}

重启服务后,Swagger文档即可正常加载。

内容的提问来源于stack exchange,提问作者Abriti Ghosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.19 11:42:37