-1

I've spent too much time on this problem, and I think i'm just doing something wrong, and there's a better way to do this.

I am creating a website with a react frontend and flask backend, with sqlite database. My issue is that when I am using session.get() it returns None in one function but not another.

In this function, the session.get() returns the correct user id and therefore the function is able to add the data to the database correctly. Even when I sign in as a different user, and the user id changes.

@app.route('/addlist', methods=['GET','POST'])
def addlist():
    if request.method == 'POST':
        user_id = session.get("user_id")
        list_name = request.form['ListName']
        color = request.form['color']
        new_list = ListOfLists(user_id = user_id,name = list_name,color=color)
        db.session.add(new_list)
        db.session.commit()
        return redirect('http://localhost:3000/userPage')

but when I try to get the lists in the frontend, session.get('user_id') returns None, and so I can not get the user's lists.

@app.route('/getlists', methods=['GET', 'POST'])
def getlists():
    user_id = session.get('user_id')
    print("USER ID: {}".format(user_id))
    lists = ListOfLists.query.filter_by(user_id=1).all()
    return jsonify(lists)

print output: USER ID: None

the function itself definitely works because when I changed .filter_by(user_id=user_id) to .filter_by(user_id=1) where the user id in the database is 1, it actually sent the correct lists I have in the database to the frontend.


here is the app configuration, register and login endpoints, and the javascript function that gets the lists if that's of any interest:

from flask import Flask, request, redirect, session, jsonify
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_cors import CORS

#flask app initialization
app = Flask(__name__)
app.config["SECRET_KEY"] = "changeme"
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)
app.config["SESSION_TYPE"] = "sqlalchemy"
app.config['SESSION_SQLALCHEMY'] = db
Session(app)
CORS(app)

@app.route('/register', methods = ['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['email']
        password = request.form['password']
        new_user = User(username=username, password=password) #user table constructor
        db.session.add(new_user)
        db.session.commit()
        return redirect('http://localhost:3000/mainpage')

@app.route('/login', methods=['GET', 'POST'])
def Login():
    if request.method == 'POST':
        username = request.form['email']
        password = request.form['password']
        user = User.query.filter_by(username = username).first()
        if user and user.password == password:
            #save user to session
            session['user_id'] = user.id
            return redirect('http://localhost:3000/userPage')
import React, { useState, useEffect } from 'react';

export default function GetLists() {
    const [lists, setLists] = useState('');
    useEffect(() => {
        fetch('http://localhost:5000/getlists')
            .then(response => response.json())
            .then(data => console.log(data))
        },[]);
//return currently doesn't matter as I am only console.log-ing the data
    return (...);
}

EDIT 1:

I noticed the print output is USER ID: 1 (the correct user id) when I manually go to http://localhost:5000/getlists, but the output is None when I use fetch() in javascript

zebigdt
  • 17
  • 3
  • I don't think this is related to issue, but you are missing the `useEffect` dependency array. Related, what if you hit the `http://localhost:5000/getlists` outside your react code, does it return the data you expect? I don't see this being a frontend/React issue with the code provided. See that the `'/getlists'` route isn't specifying a METHOD, though I have no idea if that matters. – Drew Reese Dec 01 '21 at 23:34
  • @DrewReese Didn't notice the dependency array missing, added it. but yeah the issue is definitely with the backend, because when I query the table using a number and go to `http://localhost:5000/getlists`, it actually shows me the json data. I also added the methods but it made no difference. Thank you for answering though. – zebigdt Dec 02 '21 at 00:01
  • Well, I have next to ZERO experience with python and anything python related. If you agree that this is an issue in the backend I am inclined to remove the `react-hooks` tag as it is irrelevant. I'll leave JS and switch to React and maybe someone more familiar with the tech stack can help. – Drew Reese Dec 02 '21 at 00:07
  • @DrewReese I noticed the print output is `USER ID: 1` (the correct user id) when I manually go to `http://localhost:5000/getlists`, but the output is `None` when I use fetch(). And thanks, again. – zebigdt Dec 02 '21 at 00:11

1 Answers1

0

Your session is stored in a cookie called session. According to this article, fetch does not send cookies by default.

To include the session cookie in your request, try this:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);
Gasp0de
  • 1,199
  • 2
  • 12
  • 30