Home > Web Front-end > JS Tutorial > Why Can't My FastAPI Backend Send Cookies to My React Frontend?

Why Can't My FastAPI Backend Send Cookies to My React Frontend?

DDD
Release: 2024-12-02 01:33:10
Original
261 people have browsed it

Why Can't My FastAPI Backend Send Cookies to My React Frontend?

FastAPI: Unable to Return Cookies to React Frontend

The issue arises when FastAPI fails to return cookies to a React frontend during communication.

Code:

The Python snippet below demonstrates FastAPI code for setting a cookie:

@router.post("/login")
def user_login(response: Response, username: str = Form(), password: str = Form(), db: Session = Depends(get_db)):
    # code to authenticate and generate access token
    
    # set cookie
    response.set_cookie(key="fakesession", value="fake-cookie-session-value")
    
    return {"status": "success"}
Copy after login

In the React frontend, you're using Axios to send the request:

await axios.post(login_url, formdata)
Copy after login

Troubleshooting:

  1. Confirm Cookie Creation:

    • Ensure that the Axios POST request is successful and returns a 'status': 'success' response with a 200 status code.
  2. Enable Credentials in Axios Request:

    • Set withCredentials: true in your Axios request to allow receiving credentials, including cookies.
  3. Configure CORS:

    • Since you're using different ports for FastAPI (backend) and React (frontend), enable CORS in FastAPI to specify allowed origins. Set allow_credentials=True to allow sending and receiving credentials.
  4. Specify Allowed Origins:

    • In your CORS configuration, specify the allowed origins for your React frontend.

Corrected Axios Request:

await axios.post(login_url, formdata, {withCredentials: true})
Copy after login

Additional Considerations:

  • Same Domain: Ensure that both the backend and frontend are using the same domain. Using localhost and 127.0.0.1 as different domains will prevent cookie sharing.
  • Explicit Cookie Setting: The FastAPI response.set_cookie() function explicitly sets cookies on the response.
  • Credentials Include: The browser includes credentials in cross-origin requests when credentials: 'include' is specified in fetch() or withCredentials: true in Axios.

The above is the detailed content of Why Can't My FastAPI Backend Send Cookies to My React Frontend?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template