I've been trying for hours to send a POST request to an endpoint in my Django application from my separated VueJS frontend using Axios. The problem with my code is that whatever i try i will always get Forbidden (CSRF cookie not set.)
, and i can't use @crsf_exempt
.
I tried every possible solution i found, from changing headers names in my Axios request to setting CSRF_COOKIE_SECURE to False, nothing seems to solve this problem.
Here is my request:
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) === (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
console.log(cookieValue)
return cookieValue;
}
function req(){
this.csrf_token = getCookie('csrftoken')
axios({
method: 'post',
url: 'http://127.0.0.1:8000/backend/testreq/',
data: {
//Some data here
},
headers: {'Content-Type': 'application/json', 'X-CSRFToken': this.csrf_ftoken }
}).then(function (response) {
console.log(response)
}).catch(function (error) {
console.log(error)
});
},
The token is being sent but the outcome is always the same. The Django app is using Django-Rest-Framework too, i don't know if that's the problem.
Here is some of my settings.py (for development):
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_HEADERS = list(default_headers) + [
'xsrfheadername',
'xsrfcookiename',
'content-type',
'csrftoken',
'x-csrftoken',
'X-CSRFTOKEN',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_WHITELIST = [
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:8000",
"http://127.0.0.1:8000",
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:8000",
"http://127.0.0.1:8000",
]
CSRF_TRUSTED_ORIGINS = [
"http://localhost:8080",
"http://127.0.0.1:8080",
"http://localhost:8000",
"http://127.0.0.1:8000",
]
SESSION_COOKIE_SAMESITE = None
CSRF_COOKIE_SAMESITE = None
CSRF_COOKIE_SECURE = False
CSRF_COOKIE_HTTPONLY = False
SESSION_COOKIE_SECURE = False
I don't know what else can i try to solve this problem, any advice is appreciated