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:
1 2 |
|
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:
1 2 3 4 5 |
|
This is somewhat analogous to Python code:
1 2 3 4 |
|
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
Also by me
Django Paddle Subscriptions app
For Django-based SaaS projects.
Django GDPR Cookie Consent app
For Django websites that use cookies.