3

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.

user177
  • 111
  • 1
  • 6

1 Answers1

7

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.

user177
  • 111
  • 1
  • 6