I want to make a POST request from a React app using Axios to a Django Rest Framework backend. I have managed to get a CSRF Token from the backend but I can't manage to send it with my request, so I always get a Forbidden (CSRF cookie not set.)
error:
This is the code of my React app:
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: '[email protected]',
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);
})
}
And this is my settings.py
CSRF configuration:
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"
"OPTIONS /es/api-auth/login/ HTTP/1.1" 200 0
), but the frontend console reports an error:Access to XMLHttpRequest at 'http://127.0.0.1:8000/es/api-auth/login/' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-csrftoken is not allowed by Access-Control-Allow-Headers in preflight response
– Tahsildar