Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django-cors-headers not working at all

Well, initially I had forgotten the middleware class but after adding it just worked fine ( It was a week ago ).

Now, I am back to my workstation and I find it again not working.

The ACCESS_CONTROL_ALLOW_ORIGIN headers are not at all being set.

I have tried all that is, placing the middleware at top, before CommonMiddleware but it just doesn't work.

This is my setting.py file :

DEBUG = True

ALLOWED_HOSTS = ['*']

# Application definition
INSTALLED_APPS = [
    'account',
    'corsheaders',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'social_django',
]

# if DEBUG:
#     INSTALLED_APPS += 'corsheaders',
#     MIDDLEWARE = ['corsheaders.middleware.CorsMiddleware', ]
# else:
#     MIDDLEWARE = []

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = DEBUG

This is the response I am getting :

Date: Sun, 14 Jan 2018 09:35:09 GMT
Server: WSGIServer/0.1 Python/2.7.14+
X-Frame-Options: SAMEORIGIN
Content-Type: text/html; charset=utf-8
Content-Length: 146
like image 567
jame Avatar asked Jan 14 '18 09:01

jame


1 Answers

Access-Control-Allow-Origin is included in the response only if origin header is present in the request.

Browser adds this header automatically, so you shouldn't see CORS errors on the web page that uses your API.

For me this request returned no Access-Control-Allow-Origin:

curl -v -H "Content-Type: application/json" localhost:80/status

And this one does:

curl -v -H "Content-Type: application/json" -H "origin: *" localhost:80/status

The answer on GitHub page: https://github.com/adamchainz/django-cors-headers/issues/438

like image 59
Ivan Avatar answered Nov 15 '22 05:11

Ivan