FastAPI Cookie Not Received by React Frontend: Resolution
When using FastAPI as the backend and React as the frontend communicated via AJAX requests, cookies set by FastAPI might fail to be received by React. This inconsistent behavior can be attributed to the distinct port numbers used by both applications, which creates a cross-origin request scenario.
To address this issue, several steps are necessary:
Enable Cookie Acceptance in React:
Configure the Axios request in your React app to receive cookies by setting the withCredentials property to true. This is necessary for cross-origin requests to include credentials like cookies.
For example, in Axios:
await axios.post(url, data, {withCredentials: true}))
In Fetch API:
fetch('https://example.com', { credentials: 'include' });
By following these steps, FastAPI should successfully return cookies to your React frontend. Remember to thoroughly check that the cookie is set correctly, with no errors returned in the Axios POST request.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3