将pyyaml用于FastAPI时出现CORS错误

问题描述 投票:0回答:1

我正在尝试使用react前端和fastapi后端创建一个简单的Web应用程序。 Web应用程序的一项功能是发送文件,该文件在前端收集并在后端处理。我在后端有一个端点,看起来像:

@app.post("/upload_file/")
async def create_upload_file(file: UploadFile = File(...)):
    for line in file.file.readlines():
        print(line)
    file.file.close()
    return {"filename": file.filename}

我已确认此代码有效。从前端,我可以发送文件,观察后端终端上打印的行,前端会收到带有200状态代码和文件名的http响应。

当我尝试使用pyyaml库来处理入站yaml文件时出现问题。以下是无效的代码段:

@app.post("/upload_file/")
async def create_upload_file(file: UploadFile = File(...)):
    yaml_data = yaml.load(file, Loader=yaml.FullLoader)
    return yaml_data

我收到错误:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/upload_file/' (redirected from 'http://127.0.0.1:8000/upload_file') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

所以这似乎是一个CORS问题...我当前的FastAPI CORS政策如下:

origins = [
    "http://localhost",
    "http://localhost:3000",
    "http://127.0.0.1:8000",
]

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

我必须在我的CORS政策中添加一些内容以允许其使用pyyaml吗?我不认为会是这种情况,因为处理仍应在同一端点上进行(请注意端点在同一位置),但是CORS显然不满意使用该yaml.load()函数。能够在我的后端加载yaml文件的任何建议将不胜感激。

根据Rishabh Batra的请求,我在此处添加了OPTIONS标头:enter image description here

python cors pyyaml fastapi
1个回答
0
投票

在其他端口上运行的后端代码,您可以使用*或定义在您的应用程序上使用的所有端口

origins = [
    "http://localhost:*",
    "http://localhost:3000",
    "http://127.0.0.1:8000",
]
© www.soinside.com 2019 - 2024. All rights reserved.