我不能使用 Django 服务器发送的 cookie

问题描述

我在 Django 上创建了一个身份验证 API,当您向登录端点发送请求时,它会在响应 cookie 中发送 csrf 令牌。但它只有在我使用 Postman 或直接从浏览器发出这些请求时才有效:

Postman login

Postman Profile page access

Response from a server to an axios request

这里我们看到浏览器中没有cookies: Cookies stored in the browser after request

但是在这里我们可以清楚地看到服务器向我发送了带有 csrf 令牌和会话 ID 的 cookie。 Response cookies in the browser devtools

但我无法从响应对象访问这些 cookie。 document.cookies 和 response.headers['set-cookie'] 中都没有。我尝试了很多东西,但不幸的是什么都没有。

这就是我提出请求的方式:

const login = (url) => {
  const creds = {
    "email": "example@gmail.com","password": "hello"
  }
  axios.post(url + '/login',creds)
  .then(
    res => {
      console.log(res)
    }
  ).catch(err => console.log('ERROR: ' + err))
}

const profile = (url) => {
  axios.get(url + '/profile',{
    withCredentials: true,})
  .then(
    res => console.log(res)
  ).catch(err => console.log('ERROR: ' + err))
}

这是django中的登录视图:

@api_view(['POST'])
def login_user(request):
    user = authenticate(request,username=request.data["email"],password=request.data["password"])
    if user is not None:
        login(request,user)
        return Response('Successfully logged in!',status=status.HTTP_200_OK)
    else:
        return Response("incorrect username or password",status=status.HTTP_400_BAD_REQUEST)

如何接受所​​有cookies并将浏览器cookies设置为服务器发送的cookies?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)