React Django REST framework session is not persisting/working

大城市里の小女人 提交于 2019-12-08 13:37:07

问题


I'm working on a project with Django Rest Framework as back-end and React as front-end. When I set a session variable initially in some function/view and later when I try to access the different view through axios call and in that view if I try to access session variable which i created previously, I get KeyError. Session doesn't seem stored.

I googled I got the similar issue which I'm facing.

Django rest framework Reactjs sessions not working

I followed the process by adding { withCredentials: true } in axios call. Now i'm getting different error. Now the issue is not able to access the backend. I get an error saying Access to XMLHttpRequest at 'http://127.0.0.1:8000/url/' from origin 'http://localhost:3000' has been blocked by CORS policy

Again I googled the issue which i'm getting and found that I've to add CORS_ORIGIN_WHITELIST in the django settings.py

I followed the below post for that

Django Python rest framework, No 'Access-Control-Allow-Origin' header is present on the requested resource in chrome, works in firefox

I have added CORS_ORIGIN_WHITELIST like this

CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000', 'http://127.0.0.1:3000' ]

Still i'm facing the same issue. I don't know whats going wrong. Can any one please help me on this issue.

Thank you.


回答1:


I had a similar issue once. I used firefox as a browser and got the problem solved by installing the CORS everywhere plugin for firefox (https://addons.mozilla.org/en-US/firefox/addon/cors-everywhere/). So, if you're using firefox, this might solve your problem.




回答2:


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

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

example:

import axios from "axios";

axios.defaults.withCredentials = true;

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

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

CORS_ORIGIN_ALLOW_ALL = True

CORS_ALLOW_CREDENTIALS = True

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. :)

NOTE

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.



来源:https://stackoverflow.com/questions/57305141/react-django-rest-framework-session-is-not-persisting-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!