我已经创建了一个登录路径,我在其中发布了我的表单数据并设置了一个 cookie。设置 cookie 后,我重定向到“/main”,在那里我得到 {detail:"Method Not Allowed"}
作为响应。
@app.post("/login")
async def login(request:Request):
response = RedirectResponse(url="/main")
response.set_cookie(key="cookie",value="key-value")
return response
@app.get("/main")
async def root(request:Request, cookie: Optional[str] = Cookie(None)):
if cookie:
answer = "set to %s" % cookie
else:
answer = "not set"
return {"value": answer}
我进一步检查了控制台,发现在重定向期间向“/main”发出了 POST 请求,因此导致了错误。当我将其更改为 app.post("/main")
时,它工作正常。如何避免此错误?我不想每次都发出访问“/main”的发布请求。提前致谢。
最佳答案
我发现在 FastAPI 中,默认情况下 starlette 响应的代码为 307,它在重定向期间保留了方法,因此保留了 post 请求。我通过在返回响应之前添加 response.status_code = 302
解决了这个问题。
关于python - FastAPI 重定向给出方法不允许的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66849929/