【发布时间】:2022-10-23 21:00:13
【问题描述】:
我有一个使用 FastAPI 后端和 Next.js 前端的应用程序。在具有稳定来源的开发和生产中,我可以毫无问题地使用 CORSMiddleware。但是,我已经使用 Vercel 部署了 Next.js 前端,并希望利用 Vercel 在每次 git 提交时进行的自动预览部署,以允许分段类型的定性测试和健全性检查。
我在预览部署中遇到了 CORS 问题:由于每个预览部署都使用模式的自动生成 URL:<project-name>-<unique-hash>-<scope-slug>.vercel.app,因此我无法将它们直接添加到allow_originsCORSMiddleware 的参数。相反,我试图将模式添加到allow_origin_regex争论。
我对正则表达式很陌生,但能够找出我已经测试过在 REPL 中工作的模式。但是,因为我遇到了问题,我已经改用“。*”的超宽松正则表达式,只是为了让任何东西都能正常工作,但这也失败了。
main.py(相关部分)
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = [
"http://localhost",
"http://localhost:8080",
"http://localhost:3000",
"https://my-project-name.vercel.app"
]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_origin_regex=".*",
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
我查看了 FastAPI/Starlette cors.py 文件以了解它如何摄取和使用原始正则表达式,但看不出问题出在哪里。我已经在 REPL 中测试了相同的方法,没有任何问题。为了解决这个问题,我不知道下一个调查途径。欢迎任何帮助或指示或“嘿,你忘了这个”cmets。
【问题讨论】:
标签: python regex fastapi vercel starlette