How to handle CORS in Django
CORS error in Django is quite common. If you want to know how to handle CORS in Django then this brief tutorial will surely help you to get started.
In the modern era of web development, we somehow come to know about CORS. CORS refers to Cross-Origin Resource Sharing. It's a mechanism to prevent access to resources of a specific web page from the external domain. Django has many in-built security options and CORS is one of them.
Django CORS helps to prevent access to resources from an external domain in a Django application. It basically throws an error like CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
We can get rid of this error by using a 3rd party package called django-cors-headers. Let's provide the required permission in the following way.
Install Django cors headers
python -m pip install django-cors-headers
this command will install the package. Now we need to add it to our INSTALLED_APPS as follows.
INSTALLED_APPS = [ ... 'corsheaders', ... ]
Once it’s added we need to add a middleware into the MIDDLEWARE list.
MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ]
These few steps will now handle CORS perfectly. All you need to do is to add a list of origins to allow as follows in your settings.py file.
CORS_ALLOWED_ORIGINS = [ "https://example.com", "https://sub.example.com", "http://localhost:8080", "http://127.0.0.1:8080" ]
Also, make sure to set the CORS_ORIGIN_ALLOW_ALL to False. You can now handle CORS in Django using this approach.