How to add CORS Headers to Django responses

Browsers by default do not allow Cross Origin Requests for security reasons. A Cross Origin Request occurs when a script on one domain attempts to get data from a different domain. Cross-Origin Resource Sharing (CORS)is a mechanism that tells web browsers to give an application in one domain access to selected resources from a different domain. When building APIs it is important to be mindful of CORS and enable it in your Django application.

The easiest way to enable CORS in Django is through a package known as django-cors-headers. This package adds CORS Headers to responses. To install django-cors-headers, run the following command in a terminal:

pip install django-cors-headers

Once it is installed, add it to your Django application’s installed apps section in the settings.py file:

INSTALLED_APPS = [
    ...
    'corsheaders',
    ...
]

Next, add a middleware class to listen in on responses:

MIDDLEWARE = [  # Or MIDDLEWARE_CLASSES on Django < 1.10
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    ...
]

The 'corsheaders.middleware.CorsMiddleware', should be placed as high as possible in the MIDDLEWARE list before any middleware that generates responses.

Next, configure what domains are whitelisted to use CORS:

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
       'http://localhost:8000',
)

2 comments on “How to add CORS Headers to Django responsesAdd yours →

Leave a Reply