Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FastAPI redirect gives method not allowed error

I have created a route for login, where I post my form data and set a cookie. After setting the cookie I redirect to "/main" where I get {detail:"Method Not Allowed"} as a response.

@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}

I furthered checked the console to find that a POST request is made to "/main" during the redirect and hence causing the error. When I change it to app.post("/main") it works fine. How do I avoid this error? I don't want to make post request to access "/main" everytime. Thanks in advance.

like image 565
user177 Avatar asked Sep 07 '26 18:09

user177


1 Answers

I found that in FastAPI, starlette response by default have code 307, which preserves the method during the redirection, hence the post request. I solved this by adding response.status_code = 302 before returning the response.

like image 154
user177 Avatar answered Sep 10 '26 08:09

user177



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!