gpt4 book ai didi

reactjs - 如何使用 Axios 将 CSRF Coo​​kie 从 React 发送到 Django Rest Framework

转载 作者:行者123 更新时间:2023-12-02 10:04:47 26 4
gpt4 key购买 nike

我想使用 AxiosReact 应用向 Django Rest Framework 后端发出 POST 请求。我已设法从后端获取 CSRF token ,但无法将其与我的请求一起发送,因此我总是收到 Forbidden(未设置 CSRF cookie。) 错误:

这是我的 React 应用程序的代码:

handleClick() {
const axios = require('axios');
var csrfCookie = Cookies.get('XSRF-TOKEN');
console.log(csrfCookie)
axios.post('http://127.0.0.1:8000/es/api-auth/login/',
{
next: '/',
username: 'admin@admin.com',
password: 'Cancun10!',
},
{
headers: {
'x-xsrf-token': csrfCookie, // <------- Is this the right way to send the cookie?
},
withCredentials = true,
}
)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
}

这是我的 settings.py CSRF 配置:

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = (
'xsrfheadername',
'xsrfcookiename',
'content-type',
'XSRF-TOKEN',
)

CORS_ORIGIN_WHITELIST = serverconfig.CORS_ORIGIN_WHITELIST
CSRF_TRUSTED_ORIGINS = serverconfig.CSRF_TRUSTED_ORIGINS
CSRF_COOKIE_NAME = "XSRF-TOKEN"

最佳答案

Django 默认使用 X-CSRFTOKEN 作为 csrf header ,参见 here 。您在 Django 设置中使用的选项 CSRF_COOKIE_NAME 仅更改 cookie 名称,默认情况下为 csrftoken,请参阅 here .

要解决您的问题,请在 axios 调用中使用此 header :headers: { 'X-CSRFTOKEN': csrfCookie }

使用以下内容:

axios.post('http://127.0.0.1:8000/es/api-auth/login/',
{
next: '/',
username: 'admin@admin.com',
password: 'Cancun10!',
},
{
headers: {
'X-CSRFTOKEN': csrfCookie,
},
},
)

此外,请从 Django 设置中的 CORS_ALLOW_HEADERS 中删除 XSRF-TOKEN,然后添加 X-CSRFTOKEN。如果您不想删除 XSRF-TOKEN,可以使用以下文档 here 安全地将 X-CSRFTOKEN 添加到 CORS_ALLOW_HEADERS

# settings.py

from corsheaders.defaults import default_headers

CORS_ALLOW_HEADERS = list(default_headers) + [
'X-CSRFTOKEN',
]

关于reactjs - 如何使用 Axios 将 CSRF Coo​​kie 从 React 发送到 Django Rest Framework,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54097524/

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