Home >Web Front-end >JS Tutorial >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"}
In the React frontend, you're using Axios to send the request:
await axios.post(login_url, formdata)
Troubleshooting:
Confirm Cookie Creation:
Enable Credentials in Axios Request:
Configure CORS:
Specify Allowed Origins:
Corrected Axios Request:
await axios.post(login_url, formdata, {withCredentials: true})
Additional Considerations:
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!