【发布时间】:2021-05-29 02:44:34
【问题描述】:
嘿,伙计们,我一直在尝试用 django set_cookie 解决问题,我在浏览器中找不到 cookie,它不起作用,但可以与邮递员一起使用。我浏览了一些 SO 答案,发现我必须在前端提供 withCredentials:true 并且我已经做到了,但它仍然不起作用。这是我的代码,有人可以告诉我其中的错误吗?
我想在登录时设置 cookie,到目前为止,我将令牌存储在本地存储中,我知道这不是一个安全的选择。
def post(self, request, format=None):
data = request.data
response = Response()
username = data.get('username', None)
password = data.get('password', None)
user = authenticate(username=username, password=password)
if user is not None:
if user.is_active:
data = get_tokens_for_user(user)
response.set_cookie(
key = settings.SIMPLE_JWT['AUTH_COOKIE'],
value = data["access"],
expires = settings.SIMPLE_JWT['ACCESS_TOKEN_LIFETIME'],
secure = settings.SIMPLE_JWT['AUTH_COOKIE_SECURE'],
httponly = settings.SIMPLE_JWT['AUTH_COOKIE_HTTP_ONLY'],
samesite = settings.SIMPLE_JWT['AUTH_COOKIE_SAMESITE']
)
csrf.get_token(request)
response.data = {"Response": "Login Successful", "data":data,}
return response
else:
return Response({"error": "User is not active"}, status=status.HTTP_404_NOT_FOUND)
else:
return Response({"error": "Invalid credentials"}, status=status.HTTP_404_NOT_FOUND)
反应前端
const handleSubmit = (e) => {
e.preventDefault();
axiosInstance
.post(url, {
username: formData.username,
password: formData.password,
})
// .then((res) => {
// localStorage.setItem('access_token', res.data.access);
// localStorage.setItem('refresh_token', res.data.refresh);
// })
.then(()=> {
history.push('/');
window.location.reload();
})
};
axiosInstance
const axiosInstance = axios.create({
baseURL: baseURL,
timeout: 5000,
headers: {
// Authorization: localStorage.getItem('access_token')
// ? 'JWT ' + localStorage.getItem('access_token')
// : null,
'Content-Type': 'application/json',
accept: 'application/json',
},
withCredentials: true
});
谢谢。
【问题讨论】:
-
Hey Danny..请告诉我你的 django 服务器 url 并用端口号反应 url。
-
您好,感谢您的回复。
django server: http://127.0.0.1:8000/和反应localhost:3000.
标签: reactjs django django-models django-rest-framework react-redux