About CORS Headers

By default, browsers don't allow making Ajax requests from one domain to another. This is blocked by Cross-Origin Resource Sharing (CORS) rules. To enable the access you can use special response headers. It's easiest to use django-cors-headers for that.

For example, to open an API for everyone, you can set these settings:

CORS_ALLOW_ALL_ORIGINS = True
CORS_URLS_REGEX = r"^/api/.*$"

Then when anything under https://example.com/api/* is accessed, the response will return the header "Access-Control-Allow-Origin": "*".

The cross-origin access can be checked with this JavaScript snippet from a website under another domain:

fetch("https://example.com/api/").then(
    response => response.json()
).then(
    data => console.log(data)
);

This is somewhat analogous to Python code:

response = requests.get("https://example.com/api/", headers={"Origin": "*"})
if response.headers.get("Access-Control-Allow-Origin") != "*":
    raise Exception("Access has been blocked by CORS policy.")
print(response.json())

Note that the existence and value of the "Access-Control-Allow-Origin" header will depend on the "Origin" request header and other CORS related request headers. For example, when you visit https://example.com/api/ in a new browser tab, the "Access-Control-Allow-Origin" won't be added, because it is not an Ajax call.

Tips and Tricks Programming Development Security Python 3 JavaScript CORS