跳转至

FastAPI 处理CORS问题

概要: 使用中间件,解决FastAPI的CORS(Cross-Origin Resource Sharing)问题

创建时间: 2023.07.28 22:23:31

更新时间: 2023.07.28 22:37:17

解决方法

下面时FastAPI官方给出的处理跨域问题的示例代码,app通过添加中间件的方式,允许特定的一组源origins进行CORS

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

app = FastAPI()

origins = [
    "http://localhost.tiangolo.com",
    "https://localhost.tiangolo.com",
    "http://localhost",
    "http://localhost:8080",
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


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

allow_origins

如上面所示,可以配置一组orgins列表,或者理解为CORS允许的白名单即可

allow_origin_regex

如果需要通过一组正则匹配的origins,可以将上面allow_origins=origins改写为

Python
allow_origin_regex='https://.*\.example\.org'

allow_methods

即允许CORS的HTTP请求方法,可以是POST GET,也可以允许全部方法,即allow_methods=["*"]

allow_headers

即允许的HTTP请求headers,允许全部即allow_headers=["*"]

参考