简体   繁体   English

Axios不存储Django会话cookie

[英]Axios not storing Django session cookie

I have a Django REST Framework API backend for my Vue app. 我的Vue应用程序有一个Django REST Framework API后端。 I'm trying to use Django sessions for anonymous users but either Django isn't sending or Axios can't read the session cookie. 我正在尝试为匿名用户使用Django会话,但是Django没有发送,或者Axios无法读取会话cookie。

A new session is being created by checking Session.objects.all().count() 通过检查Session.objects.all().count()创建一个新会话Session.objects.all().count()

I'm trying to store cart data using JWTAuthentication for authenticated users and SessionAuthentication for anonymous users. 我正在尝试使用JWTAuthentication为经过身份验证的用户存储购物车数据,并为匿名用户存储SessionAuthentication

# settings.py

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = (
    'localhost:8080',
    '127.0.0.1:8080',
)

SESSION_COOKIE_HTTPONLY = False

I've tried toggling SESSION_COOKIE_HTTPONLY in settings.py but still not able to see the cookie. 我试过在settings.py切换SESSION_COOKIE_HTTPONLY ,但仍然无法看到cookie。

When intercepting the response the CSRF cookie is sent but the session cookie isn't included. 拦截响应时,会发送CSRF cookie,但不包括会话cookie。

import axios from 'axios'
import Cookie from 'js-cookie'

axios.defaults.xsrfCookieName = 'csrftoken'
axios.defaults.xsrfHeaderName = 'X-CSRFToken'
axios.defaults.withCredentials = true
axios.interceptors.response.use(response => {
    const sessionCookie = Cookie.get()
    console.log('Cookie', sessionCookie)
    return response
})

In my DRF API tests I can see that the session cookie is in the response. 在我的DRF API测试中,我可以看到会话cookie在响应中。

Set-Cookie: sessionid=zgndujlppk4rnn6gymgg1czhv1u0rqfc; expires=Thu, 11 Apr 2019 11:27:32 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=Lax

class Test(APITestCase):
    def test_get(self):
        response = self.client.get('/store/1/')
        print(response.cookies['sessionid']

The issue was I was visiting the site at the URL localhost:8080 but the cookie was being saved under 127.0.0.1 . 问题是我在URL localhost:8080访问该站点,但cookie保存在127.0.0.1下。

Changing the URL to 127.0.0.1:8080 solved the problem. 将URL更改为127.0.0.1:8080解决了该问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM