"Origin" is the combination of protocol(e.g.
localhost), and port(e.g.
Therefore, all these are different origins.
Browsers restrict cross-origin HTTP requests initiated from scripts due to security issue. Therefore, if you want to enable CORS, you should specify allowed origins(origins that are permitted to make cross-origin requests), allowed methods(HTTP methods that are allowed for cross-origin requests), and allowed headers(HTTP request headers that should be supported for cross-origin requests) etc.
Before performing cross-domain requests, browsers will initiate "preflight" request to determine whether those requests are allowed. The preflight requests are done by
OPTIONS , which is a type of HTTP methods.
If the request meets certain conditions, browsers don't send preflight requests.
Simple requests satisfy these conditions:
- HTTP method is either:
- Apart from the headers automatically set by the user agent, the only headers which are allowed to be manually set are one of these:
text/plainare allowed as values
- If the request is made using an
XMLHttpRequestobject, no event listeners are registered on the object returned by the
XMLHttpRequest.uploadproperty used in the request
ReadableStreamobject is used in the request.
For more information about CORS, check this document.
Install CORS module:
pip install django-cors-headers
# settings.py ALLOWED_HOSTS = ['*'] # '*' is a wildcard which allows any host INSTALLED_APPS = [ ... 'corsheaders', ... ] MIDDLEWARE = [ ... 'corsheaders.middleware.CorsMiddleware', ... ] # CORS settings CORS_ORIGIN_ALLOW_ALL=True CORS_ALLOW_CREDENTIALS = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', )
For more information about django-cors-headers, check this document.
# main.py from fastapi.middleware.cors import CORSMiddleware app = FastAPI() origins = ["*"] app.add_middleware( CORSMiddleware, allow_origins=origins, allow_credentials=True, allow_methods=["*"], allow_headers=["*"], )
For more information about FastAPI CORS setup, check this document.
Install CORS extension:
pip install -U flask-cors
# main.py from flask-cors import CORS app = Flask(__name__) CORS(app)
For more information about flask-cors, check this document.