简体   繁体   English

(sqlite,Flask + React),flask session Z21D6F40CFB0511982E5220返回无。

[英](sqlite, Flask + React), flask session session.get() returns None

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.我正在创建一个带有反应前端和 flask 后端的网站,以及 sqlite 数据库。 My issue is that when I am using session.get() it returns None in one function but not another.我的问题是,当我使用 session.get() 时,它在一个 function 中返回 None 而不是另一个。

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.在此 function 中,session.get() 返回正确的用户 ID,因此 function 能够正确地将数据添加到数据库中。 Even when I sign in as a different user, and the user id changes.即使我以其他用户身份登录,并且用户 ID 也发生了变化。

@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.但是当我尝试在前端获取列表时,session.get('user_id') 返回 None,因此我无法获取用户的列表。

@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打印 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. function 本身肯定有效,因为当我将.filter_by(user_id=user_id)更改为.filter_by(user_id=1)时,数据库中的用户 id 为 1,它实际上将我在数据库中的正确列表发送到前端。


here is the app configuration, register and login endpoints, and the javascript function that gets the lists if that's of any interest:这是应用程序配置、注册和登录端点,以及 javascript function 如果感兴趣的话,它会获取列表:

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:编辑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 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

Your session is stored in a cookie called session.您的 session 存储在名为 session 的 cookie 中。 According to this article , fetch does not send cookies by default.根据这篇文章,fetch 默认不发送 cookies。

To include the session cookie in your request, try this:要在您的请求中包含 session cookie,请尝试以下操作:

fetch(url, {
  credentials: "same-origin"
}).then(...).catch(...);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM