Home > Article > Backend Development > How to Enable Cross-Origin Resource Sharing (CORS) in Django REST Framework using django-cors-headers?
Enabling CORS in Django REST Framework with django-cors-headers
Django REST Framework provides an easy way to include a RESTful API in Django applications. However, by default, Django's security settings prevent cross-origin requests. To enable cross-origin resource sharing (CORS), you can utilize the django-cors-headers third-party library.
How to Enable CORS
python -m pip install django-cors-headers
Edit your Django application's settings.py file and add 'corsheaders' to your INSTALLED_APPS list:
INSTALLED_APPS = ( ... 'corsheaders', ... )
Extend your MIDDLEWARE setting to include the CorsMiddleware from django-cors-headers:
MIDDLEWARE = [ ..., 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ..., ]
To specify the domains that are allowed to make cross-origin requests, edit the CORS_ALLOWED_ORIGINS setting:
CORS_ALLOWED_ORIGINS = [ 'http://localhost:3030', # Add additional allowed origins as needed ]
Refer to the django-cors-headers documentation for a comprehensive list of CORS configuration settings, including setting custom headers, expiration times, and more.
Note: To enable CORS specifically for Django REST Framework, you can use the @action decorator with the cors_allowed_origins parameter.
The above is the detailed content of How to Enable Cross-Origin Resource Sharing (CORS) in Django REST Framework using django-cors-headers?. For more information, please follow other related articles on the PHP Chinese website!