How to Fix Django CORS Error
Fix Django Cors error using django-cors-headers
Join the DZone community and get the full member experience.
Join For Free
One of the common errors we get each time when we consume Django API is CORS error.
The error might say something like: Access to XMLHttpRequest at 'url’' from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Django comes with a bunch of securities. CORS (Cross-origin resource sharing) permission request is one of them. A request for a resource outside of the origin is known as a cross-origin request. The web page from outside the domain is requesting Django to share its resources. And Django is not giving permission.
i.e. Access to Django page and resource has blocked by CORS policy.
Now, let's see how to give a permission and solve the error in Just 4 steps:
Step 1 - Install django-cors-headers
xxxxxxxxxx
pip install django-cors-headers
Step 2 - Add corsheader to the Installed App list in settings.py
xxxxxxxxxx
INSTALLED_APPS = [
...
'corsheaders',
...
]
Step 3 - Add CorsMiddleware to middleware list in settings.py
xxxxxxxxxx
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
...
]
Step 4 - You have two alternatives here. Either follow Option A or Option B
Step 4 ( Option A) - Allow access to all domains by just Adding the following variables in settings.py:
xxxxxxxxxx
ALLOWED_HOSTS=['*']
CORS_ORIGIN_ALLOW_ALL = True
Step 4 ( Option B) - Do not allow access to all the domains, but the one which you are consuming the API. Add following variables in settings.py
ALLOWED_HOSTS=['http://localhost:5000']
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
'http://localhost:5000',
)
You are good to go now. Thanks for reading
Opinions expressed by DZone contributors are their own.
Comments