Hello @kartik,
Take the following steps to enable CORS for Rest API hosted in Django application. I assume you already have REST API developed and hosted. I just focus on how to allow resources to be accessed from cross domain.
- Install django-cors-headers using PIP as follows:
pip install django-cors-headers
- Add corsheaders to installed applications in settings file:
INSTALLED_APPS = [ ... 'corsheaders', ]
- Add corsheaders.middleware.CorsMiddleware to middleware section in settings file:
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', ... ]
- Allow access to all domains by setting the following variable to TRUE in settings file:
CORS_ORIGIN_ALLOW_ALL = True
- Alternatively, you can specify which domains must be given access by creating following variables in settings file:
CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:4200', )
That's all you have to do to access resources of django application from other applications hosted on other servers.
Hope it helps!
Thanks!