可以在ajax请求的响应中得到django设置的cookies

can get the cookies set by django in the response of ajax request

cors-headers 在我的 django 服务器上启用 cors。我的setting.py是这样的

CORS_ORIGIN_ALLOW_ALL= True
CORS_ALLOW_CREDENTIALS = True

我还添加了 corsheadersINSTALLED_APPS 而我的 MIDDLEWARE 是这样的

MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'corsheaders.middleware.CorsMiddleware',

]。 我已经设置了一个非常简单的视图,看起来像这样。

    def get(self, request):

    response = HttpResponse("hi")
    response['Set-Cookie'] = ('food=bread; Path=/; max_age=10000')
    print(response._headers)
    return response

在控制台上 headers 是这样的。

{'set-cookie': ('Set-Cookie', 'food=bread; drink=water; Path=/; max_age=10000'), 'content-type': ('Content-Type', 'text/html; charset=utf-8')}

当我在浏览器中调用我的 api 时,cookie 已设置并且一切正常但是当我在响应的 body 中将 axios 用于 ajax 时,没有任何类似于我的饼干。 我喜欢这样的 javasctipt 代码。

 axios.get('http://37.130.202.188:13434/users/test/',
  {withCredentials: true,

 })
  .then(function (response) {
    console.log(response);
  });

我 运行 我的服务器使用此命令

python manage.py runserver

非常感谢对这种头痛的每一个回应。

我找到了答案。与 this question 完全一样,在 http 响应的 headers 中设置的 cookie 在 Javascript 中不可访问,它们会自动保存在浏览器中。