问题描述
我开始使用rest API和react js构建带有JWT令牌身份验证的基本身份验证系统。但是,我在从使用 rest_framework.response.Response 对象发送的 Django 视图设置 cookie 时遇到了一个问题。现在,问题是在 Django 服务器中设置了 cookie,但在这种情况下,当与 react js 集成时它失败了。 Django 服务器在 8000 端口上运行并在 3000 上响应 js。
@api_view(['POST'])
def login(request):
try:
username = request.data['username']
password = request.data['password']
user = authenticate(request=request,username=username,password=password)
if user:
refresh = RefreshToken.for_user(user)
response = Response()
response.data = {
"status": True,"Access": str(refresh.access_token)
}
response.set_cookie(key='refreshtoken',value=(refresh),httponly=True,samesite=None)
return response
else:
return Response(FALSE_RESPONSE)
except Exception as e:
print(e)
return Response(FALSE_RESPONSE)
这是 axios 请求,我是从前端提出的。
axios({
method: "POST",url: "http://localhost:8000/user-api/login/",data: {
username:username,password:password
},credentials: 'include',withCredentials: true
})
.then(response => {
console.log(response)
if(response.data['status']) {
setAccesstoken(response.data['Access'])
setIsAuthenticated(true)
setLoginModal(false)
} else {
alert("Error! Credentials doesn't match.")
}
})
.catch(error => {
console.log(error)
})
这个 axios 请求没有产生错误,我成功获取了令牌,但刷新令牌没有保存在 cookie 中。
# settings.py
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000","http://127.0.0.1:3000"
]
CORS_ALLOW_CREDENTIALS = True
帮我解决这个问题!!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)