【发布时间】:2019-06-03 11:36:20
【问题描述】:
我想使用 Axios 从 React 应用向 Django Rest Framework 后端发出 POST 请求.我已经设法从后端获得 CSRF 令牌,但我无法将它与我的请求一起发送,所以我总是收到 Forbidden (CSRF cookie not set.) 错误:
这是我的 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"
【问题讨论】:
标签: reactjs django-rest-framework axios csrf django-csrf