I have an application based FastAPI Which serves as the backend for a website And currently deployed on a server with an external IP. The frontend is situated at another developer, temporarily in local hosting. At the beginning of the work we encountered a CORS problem, which was solved by using the following code I found on the Internet:
from fastapi.middleware.cors import CORSMiddleware
...
app.add_middleware(
CORSMiddleware,
allow_origins=['http://localhost:3000'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
The addition allowed Frontend to make requests properly, but for some reason, cookies that are set to send (and work properly in the Swagger UI) are not set in Frontend. The client side look like:
axios({
method: 'POST',
baseURL: 'http://urlbase.com:8000',
url: '/login',
params: {
mail: '[email protected]',
password: 'xxxxxx'
},
withCredentials: true
}).then( res => console.log(res.data) )
.catch( err => console.log(err))
In FastAPI you can set cookies via
response.set_cookie
,It should be noted though that these are NOT SECURE SESSIONS you should use something like itsdangerous to create encrypted sessions.
In response to the requests not seeming to not be sent; You should make sure the option for which urls the cookies are valid for are being set. By default they are typically
/
which means everything however your system might be setting them to a specific case with CORS setup.