django-cors-headers
- Install the
django-cors-headers
package using pip:
pip install django-cors-headers
- Add
'corsheaders'
to theINSTALLED_APPS
list in your Django project's settings:
INSTALLED_APPS = [
# ...
'corsheaders',
# ...
]
- Add
'corsheaders.middleware.CorsMiddleware'
to theMIDDLEWARE
list in your settings:
MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
# ...
]
- Configure CORS settings in your project's settings:
CORS_ALLOWED_ORIGINS = [
# add the domains or IPs that are allowed to make cross-origin requests
"http://localhost:3000", # example: your frontend development server
"https://yourproductiondomain.com",
# ...
]
# Optional: Allow credentials (cookies, authentication headers) to be included in cross-origin requests
CORS_ALLOW_CREDENTIALS = True
- (Optional) Fine-tune CORS settings based on your requirements:
# Example: Allow specific HTTP methods
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
# Example: Allow specific headers in the cross-origin request
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
# Example: Set the maximum age (in seconds) for which the CORS preflight response is cached
CORS_PREFLIGHT_MAX_AGE = 3600
- Run migrations to apply the changes to your database:
python manage.py migrate
- Start your Django development server:
python manage.py runserver
Your Django application is now configured to handle Cross-Origin Resource Sharing (CORS) using the django-cors-headers
package.