I’m building a web app that consists of a React frontend and a Flask backend. The React application is hosted on port 8000, while the Flask server is on port 5000. I’m implementing a booking system that captures user information in the first step and retrieves it in the second step using Flask session management.
The Issue:
I’m facing a problem where the session data is lost when making requests, and I repeatedly encounter CORS errors. The console displays: “Access to fetch at ‘http://127.0.0.1:5000/api/…’ from origin ‘http://localhost:8000’ has been blocked by CORS policy.”
Here’s my code configuration:
# Flask configuration
from flask import Flask, session
from flask_cors import CORS
from flask_session import Session
def setup_app():
server = Flask(__name__)
server.config['SECRET_KEY'] = 'my-secret-key'
# Session settings
server.config['SESSION_TYPE'] = 'filesystem'
server.config['SESSION_COOKIE_SECURE'] = False
server.config['SESSION_COOKIE_HTTPONLY'] = True
server.config['SESSION_COOKIE_SAMESITE'] = 'None'
Session(server)
# CORS settings
CORS(server,
supports_credentials=True,
resources={r"/api/booking*": {"origins": "http://localhost:8000"}}
)
return server
// Handling requests on the frontend
// First step
await fetch(`${BASE_URL}/api/booking-step-one/${id}`, {
method: 'POST',
credentials: 'include',
body: JSON.stringify(formData)
});
// Second step
const response = await fetch(`${BASE_URL}/api/booking-step-two/${id}`, {
credentials: 'include'
});
I suspect the conflict might stem from using both localhost and 127.0.0.1 in different parts. Can someone guide me on how to adjust the CORS settings and ensure that session cookies function correctly between my React frontend and Flask backend?