A Django App that adds CORS (Cross-Origin Resource Sharing) headers to responses.
Although JSON-P is useful, it is strictly limited to GET requests. CORS builds on top of XmlHttpRequest to allow developers to make cross-domain requests, similar to same-domain requests. Read more about it here: http://www.html5rocks.com/en/tutorials/cors/
Install by downloading the source and running:
python setup.py install
or
pip install django-cors-headers
and then add it to your installed apps:
INSTALLED_APPS = (
...
'corsheaders',
...
)
You will also need to add a middleware class to listen in on responses:
MIDDLEWARE_CLASSES = (
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
)
Note that CorsMiddleware
needs to come before Django's CommonMiddleware
if you are using Django's USE_ETAGS = True
setting, otherwise the CORS headers will be lost from the 304 not-modified responses, causing errors in some browsers.
CORS_ALLOW_ORIGIN: A list of tuples consisting of a regex pattern and a list of origin hosts or the string “*”
Example:
CORS_ALLOW_ORIGIN = (
(r’^/api/account/.*$’, [‘https://app.example.com’, ‘https://app.example.fr’]),
(r’^/api/.*$’, ‘*’),
)
Default:
CORS_ALLOW_ORIGIN = ()
You may optionally specify these options in settings.py to override the defaults. Defaults are shown below:
CORS_EXPOSE_HEADERS: specify which HTTP headers are to be exposed to the browser
Default:
CORS_EXPOSE_HEADERS = ()
CORS_PREFLIGHT_MAX_AGE: specify the number of seconds a client/browser can cache the preflight response
Note: A preflight request is an extra request that is made when making a "not-so-simple" request (eg. content-type is not application/x-www-form-urlencoded) to determine what requests the server actually accepts. Read more about it here: [http://www.html5rocks.com/en/tutorials/cors/](http://www.html5rocks.com/en/tutorials/cors/)
Default:
CORS_PREFLIGHT_MAX_AGE = 86400
CORS_ALLOW_CREDENTIALS: specify whether or not cookies are allowed to be included in cross-site HTTP requests (CORS).
Default:
CORS_ALLOW_CREDENTIALS = False
v0.13 and onwards - Release Notes
v0.12 - Added an option to selectively enable CORS only for specific URLs
v0.11 - Added the ability to specify a regex for whitelisting many origin hostnames at once
v0.10 - Introduced port distinction for origin checking; use urlparse
for Python 3 support; added testcases to project
v0.06 - Add support for exposed response headers
v0.05 - fixed middleware to ensure correct response for CORS preflight requests
v0.04 - add Access-Control-Allow-Credentials control to simple requests
v0.03 - bugfix (repair mismatched default variable names)
v0.02 - refactor/pull defaults into separate file
v0.01 - initial release
A shoutout to everyone who has contributed: