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 requirest 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
pip install django-cors-headers
Step 2 - Add corsheader to the Installed App list in settings.py
INSTALLED_APPS = [
Step 3 - Add CorsMiddleware to middleware list in settings.py
MIDDLEWARE = [
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:
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
CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
You are good to go now. Thanks for reading
Opinions expressed by DZone contributors are their own.
Seven Steps To Deploy Kedro Pipelines on Amazon EMR
Health Check Response Format for HTTP APIs
Microservices With Apache Camel and Quarkus (Part 2)
Introduction To Git