In Django, a popular web framework for Python, and Django REST framework (DRF), a powerful toolkit for building APIs, you can enable Cross-Origin Resource Sharing (CORS) to allow cross-origin requests from web browsers. CORS is a security feature implemented by web browsers that restricts web pages from making requests to a different domain than the one that served the web page. Here’s an example of how you can enable CORS in Django REST framework:
- Install the
django-cors-headers
library usingpip
:
pip install django-cors-headers
- Add
'corsheaders'
to theINSTALLED_APPS
setting in your Django project’s settings.py file:
INSTALLED_APPS = [
# ...
'corsheaders',
# ...
]
- Add the
'corsheaders.middleware.CorsMiddleware'
middleware to theMIDDLEWARE
setting in your Django project’s settings.py file:
MIDDLEWARE = [
# ...
'corsheaders.middleware.CorsMiddleware',
# ...
]
- Configure CORS settings in your Django project’s settings.py file. For example:
CORS_ORIGIN_ALLOW_ALL = True
The CORS_ORIGIN_ALLOW_ALL
setting is set to True
, which allows any origin to access your Django REST framework APIs. You can also specify specific origins or configure other CORS-related settings, such as CORS_ALLOW_CREDENTIALS
, CORS_ALLOW_METHODS
, CORS_ALLOW_HEADERS
, and others, based on your specific requirements. Here’s an example:
CORS_ORIGIN_WHITELIST = (
'http://example.com',
'http://localhost:3000',
)
CORS_ALLOW_METHODS = (
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS'
)
CORS_ALLOW_HEADERS = (
'Content-Type',
'Authorization',
# Add other custom headers here
)
CORS_ALLOW_CREDENTIALS = True
In this example, the CORS_ORIGIN_WHITELIST
setting specifies a list of allowed origins. The CORS_ALLOW_METHODS
setting specifies the allowed HTTP methods for cross-origin requests. The CORS_ALLOW_HEADERS
setting specifies the allowed request headers for cross-origin requests. The CORS_ALLOW_CREDENTIALS
setting is set to True
, which allows sending credentials (such as cookies) with cross-origin requests. You can customize these options based on your specific requirements.
After enabling CORS in Django REST framework, your APIs should be able to accept cross-origin requests from the specified origins, methods, and headers, as configured in your settings.
+ There are no comments
Add yours