【问题标题】:Do I have to use Redux with React for authentication?我必须使用 Redux 和 React 进行身份验证吗?
【发布时间】:2020-04-27 00:13:22
【问题描述】:
这可能是一个愚蠢的问题。
所以,我使用 Django 作为后端,使用 React 作为前端。目标是仅显示属于发出请求的用户的对象。由于 Django 负责身份验证,我是否需要使用 Redux 或任何其他框架来进行身份验证?
当我从我的前端收到 Axios 请求时,我不能在我的后端做类似的事情:request.user.something.objects.all() 吗? Axios 请求甚至提供给用户吗?
【问题讨论】:
标签:
django
reactjs
redux
axios
【解决方案1】:
是的,您可以将数据存储在 rudex 中,这就是为什么逻辑上您也可以使用 rudex 存储作为身份验证。但是如果您更改路线或刷新页面,此数据将被破坏。 axios 一般发送 Brear?Basic authentication 。为此,您还需要像这样配置后端 api。您还可以使用浏览器会话存储或 localstorage 进行身份验证。为此,您必须从您的标头请求中传递身份验证代码,例如 as 。
fetch(URL+'/api/user/profile', {
method: 'GET',
headers: {
'Authorization': 'Bearer ' + sessionStorage.getItem('token')
}
}).then(response => {
return response.json();
})
.then(profile => {
// console.log(profile);
this.setState({
profile : profile[0]
});
});
【解决方案2】:
没有。 Redux 是可选的。将令牌存储在本地存储中,您可以使用 mobx、redux 和 context api 进行用户身份验证