Issue
When I try to access my Django rest framework from the frontend I get this error and the data is not passed along
Access to fetch at 'http://localhost:8000/api/students' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
I tried using django-cors-headers and every setting for it that I could find online; absolutely nothing worked.
Here are the settings from my settings.py file (currently commented out)
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'corsheaders',
'students'
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'project.middleware.CustomCorsMiddleware',
'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',
]
# clickjacking not compatible with corsheaders?
CORS_ORIGIN_ALLOW_ALL = True
# CORS_ALLOW_CREDENTIALS = True
# CORS_ORIGIN_WHITELIST = [
# "http://localhost:8000",
# "http://127.0.0.1:8000",
# "http://localhost:5173",
# "http://127.0.0.1:5173",
# ]
# CORS_ALLOW_HEADERS = ['*']
#
# CSRF_TRUSTED_ORIGINS = [
# "http://localhost:8000",
# "http://127.0.0.1:8000",
# "http://localhost:5173",
# "http://127.0.0.1:5173",
# ]
I also tried using custom middleware that I found here on stack overflow.
class CustomCorsMiddleware:
def __init__(self, get_response):
self.get_response = get_response
# One-time configuration and initialization.
def __call__(self, request):
# Code to be executed for each request before
# the view (and later middleware) are called.
response = self.get_response(request)
response["Access-Control-Allow-Origin"] = "*"
response["Access-Control-Allow-Headers"] = "*"
# Code to be executed for each request/response after
# the view is called.
return response
I did not try to use the custom middleware and django-cors-headers together.
I must have spent at least a day on this nonsense. I'd really appreciate a working solution or at least a workaround!
PS: I am following this tutorial https://www.youtube.com/watch?v=7GWKv03Osek&t=189s He doesn't have the same problems that I am though.
Solution
Clearing my browsing data in my browser made it work.
Answered By - vaultdweller
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.