I have an Django project that runs on Apache. With Javascript and Python i make request on diffrent sites. I always get following error:
Access to XMLHttpRequest at 'site' from origin 'site2' has been blocked
I already tried diffrent things. I installed django-cors-headers and edited my files:
Settings.py:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 'webpack_loader',
'corsheaders',
'projects',
'viewer',
'api_manager',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.RemoteUserMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_ALLOW_ALL = True
In my HTML i added following to the form:
<form class="d-flex flex-column" id="loginForm">
{% csrf_token %}
</form>
With the following method i was able to get a CSRF Token:
static getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
let cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
let 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;
}
}
}
return cookieValue;
}
And the call which needs CORS i already tried to add the correct Headers:
xhr.addEventListener('readystatechange', function () {
if (this.readyState === 4) {
if (this.status != 200) {
console.log("Error", this.statusText);
}
}
});
xhr.onerror = function(e) {
console.log("Error: " + e + "URL: " + url);
}
xhr.open(method, url, false);
xhr.setRequestHeader('Authorization', auth);
xhr.setRequestHeader('Content-Type', 'application/json');
// xhr.setRequestHeader('Access-control-allow-origin', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
var token = Fetcher.getCookie('csrftoken');
console.log(token);
xhr.setRequestHeader('X-CSRFToken', token);
xhr.send(data);
I dont know what I am missing. Does anyone know what i need to edit?
2
Answers
Add this at the end of your settings.py file.
Add these things, in your
settings.py
file as follows (if you haven’t added yet)…May be it’ll work for you. And, as you’ve added
corsmiddleware
to the middlewares you may check this guide once: django-cors-headers. Also, you can try with…Update with jquery…
I’m not sure though, either it’ll work for you or not, but you can try.