Cross-Origin Resource Sharing (CORS)
django-cors-headers
Installation
pip install django-cors-headers
Settings.py
INSTALLED_APPS = ( ... 'corsheaders', ... ) MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', ... )- Note that
CorsMiddlewareneeds to come before Django'sCommonMiddlewareif you are using Django'sUSE_ETAGS = Truesetting, otherwise the CORS headers will be lost from the 304 not-modified responses, causing errors in some browsers.
- Note that
Usage
- Add hosts that are allowed to do cross-site requests to
CORS_ORIGIN_WHITELISTor setCORS_ORIGIN_ALLOW_ALLtoTrueto allow all hosts. - CORS_ORIGIN_WHITELIST: specify a list of origin hostnames that are authorized to make a cross-site HTTP request.
- Add hosts that are allowed to do cross-site requests to
DIY
middleware.py
class AccessControlAllowOriginMiddleware(object): def process_response(self, request, response): response['Access-Control-Allow-Origin'] = '*' return responsesettings.py
MIDDLEWARE_CLASSES += ('xxx.middleware.AccessControlAllowOriginMiddleware', )
References
[1] ottoyiu@Github, django-cors-headers — Django app for handling the server headers required for Cross-Origin Resource Sharing (CORS)