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 OKContent-Type: application/jsonVary: Accept, origin,Accept-EncodingAllow: GET, HEAD, OPTIONSX-Frame-Options: DENYX-Content-Type-Options: nosniffReferrer-Policy: same-originCross-Origin-Opener-Policy: same-originAccess-Control-Allow-Origin: https://web.example.comAccess-Control-Allow-Credentials: trueContent-Length: 1884Date: Sat, 03 Feb 2024 22:01:07 GMTAlt-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.