gpt4 book ai didi

reactjs - Django REST 和 React - JWT Cookie 未在浏览器中设置但与 postman 一起工作

转载 作者:行者123 更新时间:2023-12-04 08:02:22 25 4
gpt4 key购买 nike

嘿伙计们,我被困在试图用 django 解决这个问题 set_cookie , 我在浏览器中找不到 cookie 并且它不起作用但可以与 postman 一起使用。我浏览了一些 SO 答案,发现我必须提供 withCredentials:true在前端,我已经这样做了,但仍然不起作用。这是我的代码,有人可以告诉我其中的错误吗?
我想在登录时设置 cookie,截至目前我将 token 存储在本地存储中,我开始知道这不是一个安全的选择。

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)
react 前端
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();
})
};
实例
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
});
谢谢你。

最佳答案

下设置后端和前端同IP .前任。后端是

localhost:8000

py manage.py runserver localhost:8000
和前端是(默认情况下):

localhost:3000


不同端口相同IP .
see this

关于reactjs - Django REST 和 React - JWT Cookie 未在浏览器中设置但与 postman 一起工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66390562/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com