gpt4 book ai didi

javascript - 如何在 `csrftoken` 的配置中获取 Cookies 的 `Axios.interceptors.request`?

转载 作者:行者123 更新时间:2023-11-30 20:40:37 24 4
gpt4 key购买 nike

如何在 Axios.interceptors.request 的配置中获取 Cookies 的 csrftoken

Axios.interceptors.request.use(
config => {

if (
config.method === "post" ||
config.method === "put" ||
config.method === "delete"||
config.method === "get"
) {

}


if (Cookies.get('token')!==undefined) {
config.headers['Authorization']= 'Token '+Cookies.get('token');
}
// there I try to get the `csrftoken` in the Cookies, but I can not get.
if (Cookies.get('csrftoken')!==undefined) {

config.headers['x-csrftoken']= Cookies.get('csrftoken'); // 'CSRFToken'
}

return config;
},
error => {
return Promise.reject(error.data.error.message);
}
);

Axios.interceptors.request的配置中我无法获取Cookies的csrftoken:Cookies.get('csrftoken')

我的 AxiosConfig 代码如下:

AxiosConfig:{
baseURL: 'http://10.10.10.105:8001/',

responseType: "json",
withCredentials: true, // there will send the Cookie (with it there are: sessionid, csrftoken)

xsrfCookieName: 'csrftoken', // default: XSRF-TOKEN
xsrfHeaderName: 'x-csrftoken', // default: X-XSRF-TOKEN
headers: {
"Content-Type": "application/json;charset=utf-8"
}
}

edit-1

Cookie中有csrftoken

enter image description here


edit-2

并且在cookie中,也没有csrftoken

enter image description here


edit-3

如果我在控制台中获得 document.cookie,我将获得 "":```

document.cookie
< "" ```


edit-4

在我的 Django 后端,settings.py:

INSTALLED_APPS:

...
'corsheaders',

'rest_framework',
'rest_framework.authtoken',
'rest_framework_docs',
'rest_auth',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
...

我不确定rest_authallauth是否会影响csrftoken

最佳答案

首先,始终确保 cookie 未被标记为 httpOnly .

如果是,您的 javascript 代码将无法读取/修改其内容。

您可以检查浏览器中的 cookies 选项卡,您会看到它是否可读。

但在您的情况下,django 不应将标志设置为 httpOnly 作为 docs描述如何直接从 cookie 中读取 javascript 中的值。

我可以根据经验指出一些事情:

  • 当您在拦截器中接收数据时,配置对象可能尚未填充数据。因此设置 config.headers = ...; 可能会触发错误。

确保你写:

config.headers = config.headers || {}; 

在设置 headers 之前,不会触发 'config.headers is undefined'

  • 或者直接读取 cookie,按照默认程序将 csrf 值存储在隐藏的 input 中。

你可以这样做(语法可能不正确):

<input type="hidden"
name="csrftoken"
value="{% csrf_token %}"/>
</div>

然后在拦截器中发送 token :

config.headers['x-csrftoken'] = document.querySelector('input[name="csrftoken"]').value;

在这种情况下,由于您不需要读取 cookie,将其设置为 httpOnly 将是一个巨大的优势

关于javascript - 如何在 `csrftoken` 的配置中获取 Cookies 的 `Axios.interceptors.request`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49312473/

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