Enabling Cors — Django
Build a Product Review Backend with DRF — Part 6
What is Cors?
Cross Origin Resource Sharing (CORS) is a security mechanism that allows a web page from one domain or origin to access a resource with a different domain. Server knows where a request is coming from and can choose whether or not to accept the request based on this.
We can use test-cors.org for testing CORS requests.
Enter your api url in “Remote URL” and submit request. When CORS not enabled, the result will look like the following
We’ll use dango-cors-headers package for enabling cors.
A Django App that adds Cross-Origin Resource Sharing (CORS) headers to responses. This allows in-browser requests to your Django application from other origins.
First we need to install django-cors-headers package
pip install django-cors-headers
After installation completes, add corsheaders INSTALLED_APPS:
We need to add a middleware class to listen in on responses. CorsMiddleware should be placed before CommonMiddleware or other middlewares which can generate responses. Open medium/settings.py file and type the following lines of code:
Configuration
CORS_ALLOWED_ORIGINS : A list of origins that are authorized to make cross-site HTTP requests.
CORS_ALLOWED_ORIGINS = [
"https://www.safesite.com",
]
CORS_ALLOW_ALL_ORIGINS : If True, all origins will be allowed. Setting this to True can be dangerous, as it allows any website to make cross-origin requests to yours.
CORS_ALLOW_ALL_ORIGINS = True
CSRF_TRUSTED_ORIGINS : A list of hosts which are trusted origins for unsafe requests. If you need cross-origin unsafe requests over HTTPS, continuing the example, add “subdomain.safesite.com” to this list.
CSRF_TRUSTED_ORIGINS = [
'www.safesite.com',
]
CORS_ALLOW_CREDENTIALS : If True, cookies will be allowed to be included in cross-site HTTP requests.
CORS_ALLOW_CREDENTIALS = True
Detailed descriptions for django-cors-headers you can check
For enable CORS open medium/settings.py file and type the following lines of code:
We will use test-cors.org for testing CORS request again. Enter your api url in “Remote URL” and submit request.
When CORS enabled you will see it below:
(XHR Status : 200)
You can download part 6 files from
If you want to learn more about Django, do check out the documentation, django rest framework website and make sure to check out parts of this series!