Home >Backend Development >Python Tutorial >How Do I Enable CORS in Django REST Framework Using django-cors-headers?
Enabling CORS on Django REST Framework
Enabling CORS (Cross-Origin Resource Sharing) on Django REST Framework allows clients to make cross-domain requests to your API. While the Django documentation briefly mentions using middleware for this purpose, it lacks specific implementation details.
Solution Using Middleware
As suggested, you can enable CORS using the django-cors-headers library:
python -m pip install django-cors-headers
Add it to your installed apps in settings.py:
INSTALLED_APPS = ( ..., 'corsheaders', ..., )
Next, add the middleware class to your MIDDLEWARE list:
MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ..., ]
Finally, specify the allowed origins for CORS:
CORS_ALLOWED_ORIGINS = [ 'http://localhost:3030', ]
Additional Configuration
Visit the django-cors-headers documentation for advanced configuration options and CORS settings, such as:
Consult the documentation for further customization based on your specific requirements.
The above is the detailed content of How Do I Enable CORS in Django REST Framework Using django-cors-headers?. For more information, please follow other related articles on the PHP Chinese website!