会话未存储在Django的浏览器中

时间:2020-07-17 04:54:33

标签: python django reactjs

我正在尝试使用前端React TSX和后端Django来构建应用程序。我想使用SESSION_ENGINE=django.contrib.sessions.backends.signed_cookies将会话存储在浏览器中。因此,我想以类似于PHPApache来存储会话的方式来存储会话。我已经尝试了很多方法,但是仍然无法存储会话,我不断从代码中获取输出SESSION IS NOW SET。任何帮助都会很棒。谢谢

login.tsx

import Cookies from "js-cookie";
import axios, { AxiosResponse, AxiosError } from "axios";

..........
..........

axios.request({
    url: "login/",
    baseURL: "http://localhost:8000/",
    method: "POST",
    data: data,
    timeout: 15000,
    withCredentials: true,
    headers: { "X-Requested-With": "XMLHttpRequest", "X-CSRFToken": Cookies.get("csrftoken") },
    validateStatus: () => true
}).then((res: AxiosResponse): void => {
    console.log(res.data);
});

login.py

from django.http import HttpResponse

def get(req):
    req.session.modified = True

    if req.session.get("user_id", False):
        return HttpResponse("EXISTS: " + req.session.get("user_id"))   <-- THIS OUTPUT IS NEVER BEING RETRIEVED
    else:
        req.session["user_id"] = "USER-ID"
        req.session.save()
        return HttpResponse("SESSION IS NOW SET")   <-- THIS IS THE ONLY OUTPUT BEING RETRIEVED

settings.py

..........
..........

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders'
]

SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
SESSION_EXPIRE_AT_BROWSER_CLOSE = True
SESSION_COOKIE_HTTPONLY = True
SESSION_COOKIE_SECURE = True
SESSION_COOKIE_NAME = "sessioninfo"

CORS_ORIGIN_WHITELIST = [ "http://localhost:5000" ]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ["GET","POST"]
CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ]

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True

..........
..........

1 个答案:

答案 0 :(得分:0)

我知道了。我要做的就是将settings.py编辑为此:

..........
..........

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'corsheaders'
]

SESSION_ENGINE = "django.contrib.sessions.backends.signed_cookies"
SESSION_COOKIE_NAME = "user_session"
SESSION_COOKIE_HTTPONLY = True
SESSION_SAVE_EVERY_REQUEST = True
SESSION_EXPIRE_AT_BROWSER_CLOSE = True

CORS_ORIGIN_WHITELIST = [ "http://localhost:5000" ]
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = ["GET","POST"]
CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with" ]

CSRF_COOKIE_SECURE = True
CSRF_COOKIE_HTTPONLY = True

..........
..........