【发布时间】:2021-05-05 15:13:57
【问题描述】:
由于某种原因,服务器设置的 cookie 没有被保存,无法从我的 js 代码中访问它们,在 cookie 部分的应用程序选项卡的 devtools 中,它都是空的,但是当我在第一个,那些显然没有保存的cookie被包含在标题中。
我已在 axios 配置中将 withCredentials 设置为 true,并在我的后端将 CORS_ALLOW_CREDENTIALS 设置为 true。
以下是应保存 cookie 的请求标头:
Response Header:
access-control-allow-credentials: true
access-control-allow-origin: <frontend url>
content-length: 22
content-type: text/html; charset=utf-8
date: Mon, 01 Feb 2021 12:04:09 GMT
server: nginx/1.19.2
set-cookie: csrftoken=<token>; expires=Mon, 31 Jan 2022 12:04:09 GMT; Max-Age=31449600; Path=/; SameSite=Lax
set-cookie: sessionid=<sessionid>; expires=Mon, 01 Feb 2021 13:04:09 GMT; HttpOnly; Max-Age=3600; Path=/
strict-transport-security: max-age=31536000
vary: Cookie, Origin
x-frame-options: SAMEORIGIN
Request Headers:
:authority: <backend url>
:method: POST
:path: /login/
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
content-length: 66
content-type: application/json;charset=UTF-8
dnt: 1
origin: <frontend url>
pragma: no-cache
referer: <current frontend url query>
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36
正如您在响应中看到的,我设置了两个 cookie,sessionid 和 csrftoken,它们没有被保存。
奇怪的是这些 cookie 出现在以下请求中:
Request Headers:
:authority: <backend url>
:method: GET
:path: /numbers/
:scheme: https
accept: application/json, text/plain, */*
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
cache-control: no-cache
cookie: csrftoken=<token>; sessionid=<sessionid>
dnt: 1
origin: <frontend url>
pragma: no-cache
referer: <current frontend url query>
sec-fetch-dest: empty
sec-fetch-mode: cors
sec-fetch-site: same-site
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36
如何可能不设置 cookie 但仍包含在请求中?什么会导致这种行为?我真的需要拯救他们。
我的后端和前端位于不同的 url,我的后端运行在带有 rest 框架的 Django 上。
更新
我还尝试将 cookies 上的 samesite 设置为 none,并将请求 content-type 更改为 application/x-www-form-urlencoded。还是没有运气。
【问题讨论】:
标签: javascript django cookies axios