I was struggling with CORS lately in my django project. I followed all needed steps like installing django-cors-headers and here is my settings.py:
INSTALLED_APPS = [
'rest_framework', # dasti ezafe shod
'rest_framework_simplejwt',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'carat', # dasti ezafe shod
'data',
'price',
'users',
'marketplace'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_WHITELIST = (
'https://example.com',
'https://web.example.com',
)
We build flutter web app and deployed in web.mydomain.com. from the beginning I faced with CORS errors but once I input those settings they all disappeared except one error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://example.com/media/images/image0_WEEP09I.png. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 200. I see this error in console tab of the inspector in firefox.
Here is a part of my server response:
HTTP/2 200 OK
Content-Type: application/json
Vary: Accept, origin,Accept-Encoding
Allow: GET, HEAD, OPTIONS
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
Referrer-Policy: same-origin
Cross-Origin-Opener-Policy: same-origin
Access-Control-Allow-Origin: https://web.example.com
Access-Control-Allow-Credentials: true
Content-Length: 1884
Date: Sat, 03 Feb 2024 22:01:07 GMT
Alt-Svc: h3=":443"; ma=2592000, h3-29=":443"; ma=2592000, h3-Q050=":443"; ma=2592000, h3-Q046=":443"; ma=2592000, h3-Q043=":443"; ma=2592000, quic=":443"; ma=2592000; v="43,46
` I am really confused, anyone can guide me how to fix it?
I added this code:
def options(self, request):
response = Response()
response["Access-Control-Allow-Origin"] = "https://example.com"
response["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response["Access-Control-Allow-Headers"] = "authorization"
return response
in my class to support options request.
You should provide a list of origins and not a tuple . also CORS_ORIGIN_WHITELIST is deprecated and you should use CORS_ALLOWED_ORIGINS like below :