且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

React Django REST框架会话无法持久/正常工作

更新时间:2023-11-19 17:39:04

最后,经过大量研究,我找到了解决方案.

Finally after so much of research I found a solution for this.

在我们要导入axios进行呼叫的文件中,将默认标头设置为您的导入下方 axios.defaults.withCredentials = true;

In the file where we are importing axios to make the call, set the default header below your import axios.defaults.withCredentials = true;

示例:

import axios from "axios";

axios.defaults.withCredentials = true;

axios.get("url")
.then(response => { 
   console.log(response) 
})
.catch(error => {
    console.log(error);
});

完成此操作后,转到您的settings.py文件并添加以下配置

once this is done go to your settings.py file and add the below configuration

CORS_ORIGIN_ALLOW_ALL =真

CORS_ALLOW_CREDENTIALS =真

因此,在此之后,如果您设置会话变量并以后在任何视图中访问它,您将能够获取先前存储的值.

so after this if you set a session variable and access it later in any view, you would be able to get the value which you had previously stored.

此解决方案对我有用.希望如果有人遇到同样的问题,它也将对他们有用. :)

This solution worked for me. Hopefully if anyone has the same issue, it will work for them too. :)

注意

如果会话未存储在 localhost:3000 下,请确保您正在通过 127.0.0.1:3000 访问应用程序.如果您通过 localhost 访问该应用程序,则cookie将存储在 127.0.0.1 下,因此将URL从 localhost:3000 更改为 127.0.0.1:3000 将解决您的问题.

If session is not storing under localhost:3000 then make sure that you're accessing your application through 127.0.0.1:3000. If you access the application through localhost then the cookie will be stored under 127.0.0.1, so by changing the URL from localhost:3000 to 127.0.0.1:3000 will solve your problem.