fastapi cors 允许 localhost 所有端口
FastAPI的 CORSMiddleware
默认不支持使用通配符 *
在端口上,即 http://localhost:*
这样的格式是无效的。但你可以使用正则表达式来解决这个问题。
你可以创建一个 originsRegex
列表来包含正则表达式,但是需要使用 allow_origin_regex
参数而不是 allow_origins
来在中间件中添加这些正则表达式。
下面是如何修改你的代码来实现这个目标:
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"https://example.com",
# ❌ "https://localhost:*", // 这样写是无效的
]
originsRegex = "|".join([
r'http://localhost:\d+', # 匹配 http://localhost:任意数字端口
r'http://127\.0\.0\.1:\d+' # 匹配 http://127.0.0.1:任意数字端口
])
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_origin_regex=originsRegex, # 使用这个参数
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
这样,你的应用应该可以接受来自 localhost
和 127.0.0.1
的任意端口的CORS请求了。
官方文档写的不是很清楚,参考
https://fastapi.tiangolo.com/tutorial/cors/ (opens in a new tab)