FastAPI CORS,允许源不起作用的通配符

FastAPI CORS, wildcard in allow origins not working

提问人:rabbibillclinton 提问时间:11/17/2023 更新时间:11/18/2023 访问量:57

问:

我的代码的简化版本,使用两种方法。

from fastapi import FastAPI

middleware = [
    Middleware(
        CORSMiddleware,
        allow_origins=["*"],
        allow_credentials=False,
        allow_methods=["*"],
        allow_headers=["*"],
    )
]

app = FastAPI(middleware=middleware)

从文档中。

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

app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

CORS 总是失败。它给了我错误(或者只是一个一般错误。我已经检查了两次、三次和百分点的标题。请求始终发送源,而 FastAPI 从不响应 .CORS Missing Allow OriginCORSAccess-Control-Allow-Origin

我觉得我在这里错过了一些非常简单的东西。我的前端使用 NextJS,并且我使用 Redis 缓存大部分请求。整个网络都在 Docker 下,我已经尝试了来自两个代理和外部代理的 CORS。我不认为这些信息是相关的,但你永远不知道。localhost

python next.js cors fastapi 中间件

评论

1赞 possum 11/17/2023
你看到预检呼叫了吗?否则,您的 API 调用是否成功?如果它返回非 200,则可能会有问题。
0赞 Yurii Motov 11/17/2023
如果显式指定来源,它是否有效?例如allow_origins=["localhost"]
0赞 Chris 11/17/2023
您可能会发现这个答案以及末尾提供的所有相关答案很有帮助。

答:

0赞 rabbibillclinton 11/18/2023 #1

错误是我使用的是 Github Codespaces,而 CORS 被搞砸了。切换到完全本地的构建就成功了。