首页 > 解决方案 > Django登录状态没有保存

问题描述

我正在使用 Django 和 React 创建登录页面。当用户单击提交按钮时,我向我的 Django 服务器发送一个请求Axios POST到. 在登录功能中,打印按预期工作。但是一旦离开函数的范围,打印就会打印. 我和一些人谈过这件事,他们似乎认为这是因为 cookie 没有持久化,但我们无法解决问题。任何指导将不胜感激。authenticateloginrequest.userrequest.userAnonymousUser

// REACT FORM 
function submitHandler(event) {
    event.preventDefault();
    const state = login ? "login" : "signup";

    axios
        .post(`http://localhost:8000/auth/${state}`, {
            username: username,
            password: password,
        })
        .then((response) => {
            setRedirectMessage(response.data);
            axios
                .post("http://localhost:8000/auth/user")
        })
        .catch((err) => alert(err.response.data));
}
# LOGIN REQUEST (/auth/login)
@require_POST
@csrf_exempt
def auth_login(request):
    if request.user.is_authenticated:
        return HttpResponseBadRequest("You are already logged in")
    username, password = get_credentials(request)
    user = authenticate(username=username, password=password)
    if user is None:
        return HttpResponseBadRequest("Those credentials do not exist")
    login(request, user)
    print(user) # PRINTS CORRECTLY
    print(request.user) # PRINTS CORRECTLY
    return HttpResponse("You have successfully logged in with username " + username)
# GET REQUEST TO CHECK LOGIN STATE (auth/user)
@csrf_exempt
def get_user(request):
    print(request.user)
    return HttpResponse("Hey there")

标签: pythonreactjsdjangoauthentication

解决方案


settings.py 中需要以下行:

CORS_ALLOW_CREDENTIALS = True

https://pypi.org/project/django-cors-headers/


推荐阅读