Reputation: 21
I'm working on a Django backend with a React frontend, where I'm facing a CORS issue specifically for GET requests with credentials enabled. The POST requests work fine, but GET requests fail with a CORS error on the preflight request.
Backend: Django with Django REST Framework and Simple JWT for authentication.
Frontend: React using axios
with withCredentials: true
.
Local Development:
Django is running locally and exposed using Ngrok (HTTPS).
React frontend is on a different machine running at 192.168.1.2:3000
or localhost:3000
.
I’ve configured django-cors-headers
to manage CORS settings.
CORS Issue: The Access-Control-Allow-Origin
header is missing in the response for GET requests, causing a CORS error.
Observations:
The POST request successfully attaches headers and completes.
The GET request triggers a preflight (OPTIONS) request, and the response from Django lacks the necessary CORS headers, leading to the error.
CORS Settings in settings.py
:
INSTALLED_APPS = [
...
'rest_framework',
'corsheaders',
'rest_framework_simplejwt.token_blacklist',
...
]
MIDDLEWARE = [
...
'corsheaders.middleware.CorsMiddleware',
'django.middleware.common.CommonMiddleware',
...
]
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"http://192.168.1.2:3000", # React frontend machine local ip
"https://<ngrok_subdomain>.ngrok-free.app",
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_ALL_ORIGINS = False
CORS_EXPOSE_HEADERS = ["Content-Type", "X-CSRFToken", "Set-Cookie"]
Sample Django GET View:
from rest_framework.views import APIView
from rest_framework.response import Response
class TestGetView(APIView):
def get(self, request):
return Response({"message": "GET works!"})
Axios Request in React:
axios.get('https://<ngrok_subdomain>.ngrok-free.app/test-get/', { withCredentials: true })
.then(response => console.log(response))
.catch(error => console.error(error));
The following CORS error appears in Chrome and Safari (but it properly works in Opera):
Verified CORS_ALLOWED_ORIGINS
includes the correct domain.
Tried using CORS_ALLOW_ALL_ORIGINS = False
(also tried with True
as a test).
Verified withCredentials: true
is set in the axios request.
Ensured the Access-Control-Allow-Origin
header is present in the POST response.
Why would CORS work with POST but not with GET in this setup, especially when everything works in Opera?
Are there any configurations or additional middleware I need to handle CORS for preflight requests on GET for Chrome and Safari?
Upvotes: 0
Views: 44