Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enabling CORS (Cross Origin Request) in Django

I'm trying to make use of the overpass API http://wiki.openstreetmap.org/wiki/Overpass_API with a JavaScript XMLHttpRequest in a project running on Django but I keep getting the

 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/accounts/ClientLogin. (Reason: CORS header 'Access-Control-Allow-Origin' missing). 

error. I get this error whether I'm using GET or POST, and from any other host, not just the overpass API.

I've installed django-cors-headers https://github.com/ottoyiu/django-cors-headers and followed the instructions there, putting 'corsheaders' into INSTALLED_APPS, and 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', into MIDDLEWARE_APPS and I've set

CORS_ORIGIN_ALLOW_ALL = true 

in settings.py but nothing seems to work. I'm running it locally with

python manage.py runserver

but I'm also hosting it on openshift. Neither on of these work, they both give the error above.

Please let me know if I am missing anything here.

like image 634
Abendsen Avatar asked Jul 20 '16 13:07

Abendsen


2 Answers

I was having the same problem while trying to access my Django Rest Framework API hosted at Heroku from my laptop (localhost). I am using Django 1.10.2, DRF 3.4.7 and python v3.4.

I did pip install django-cors-headers (version 1.2.2) and configured it as the docs say and then, the same error again :(

Keep searching for hours and then it hit me!

I did pip install django-cors-middleware (version 1.3.1) without uninstalling the django-cors-headers package. Also I didn't touch a thing in my settings.py file (it was configured as the django-cors-headers settings, although these two packages do not have many differences - the latter is a fork of the first).

Hit refresh (from localhost) and everything worked brilliantly!

I was now able to fetch data from myapp.herokuapp.com via jQuery's ajax method.

like image 108
nik_m Avatar answered Oct 05 '22 00:10

nik_m


Remember to put the 'corsheaders.middleware.CorsMiddleware' in the top of your list, and also the 'django.middleware.common.CommonMiddleware' is already a standard middleware

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.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
 ]
like image 42
Pedro Fam Avatar answered Oct 05 '22 00:10

Pedro Fam