How to enable CORS on the Django REST Framework

How to enable CORS on the Django REST Framework

When we develop rest API and want to consume from different website we have to enable cors.

In this tutorial, i will show you how to enable cors

Install package

pip install Django-cors-headers and then add it to your installed apps:

INSTALLED_APPS = ( ... 'corsheaders', ... ) You will also need to add a middleware class to listen in on responses in seetings.py:

MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... ) Now i will give two alternatives anyone you can do

ALLOWED_HOSTS=['*'] CORS_ORIGIN_ALLOW_ALL = True second alternative

ALLOWED_HOSTS=['http://localhost:5000']
CORS_ORIGIN_ALLOW_ALL
= False CORS_ORIGIN_WHITELIST = ( 'http://localhost:5000', ) Thanks for the reading blog.