1

I am making a flask + react website and I want to use session, But the session does not persist between requests.

I know it is caused because of CORS and I already solved that kind of problem in a flask + react native project but here it does not work.

My flask initialization is like so:

# Configure application
app = Flask(__name__, static_folder='front-app/build', static_url_path='')
#secret key
app.config["SECRET_KEY"] = 'secret'

# configure cors
CORS(app, supports_credentials=True)

app.config.update(
    REMEMBER_COOKIE_SECURE = True,
    SESSION_COOKIE_HTTPONLY=True,
    REMEMBER_COOKIE_HTTPONLY = True,
    SESSION_COOKIE_SAMESITE='Lax',
)

# make session permanent
@app.before_request
def make_session_permanent():
    session.permanent = True

# Ensure responses aren't cached
@app.after_request
def after_request(response):
    response.headers['Strict-Transport-Security'] = 'max-age=31536000; includeSubDomains'
    response.headers['X-Content-Type-Options'] = 'nosniff'
    response.headers['X-Frame-Options'] = 'SAMEORIGIN'
    response.headers['X-XSS-Protection'] = '1; mode=block'
    response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
    response.headers["Expires"] = 0
    response.headers["Pragma"] = "no-cache"
    return response

The route:

@app.route("/api", methods=["GET", "POST"])
@cross_origin()
def index():
if request.method == "GET":
        # create game arr
        print(session.get("wo")) # prints None every time
        session["wo"] = 1
        
        wordsArr = session.get("wordsArr")
        today = datetime.today().strftime("%Y-%m-%d")
        if wordsArr is None or session.get("date") != today:
            wordsArr = [[] for x in range(6)]
            for i in range(6):
                for k in range(5):
                    wordsArr[i].append({"letter": "", "color": ""})
            session["date"] = today
        
        selectedWord, wordCount = HelpFunc.generate_word(db, conn)
        
        return json.dumps({"wordsArr": wordsArr, "selectedWord": selectedWord, "wordCount": wordCount})

The request from react:

export const getData = async () => {
const response = await fetch('http://192.168.1.32:5000/api', {
    method: 'GET',
    credentials: 'include',
    headers: {
        'Access-Control-Allow-Origin': '*',
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
})

if (response.ok) {
    const result = await response.json()
    return result
}

const errMessage = await response.text()
throw new Error(errMessage)

}

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.