Background
I’m working on a web application that has two parts deployed on different subdomains. The frontend is a React app and the backend is a Django REST API. I’m hosting both on my own server but they can’t communicate properly due to CORS issues.
Setup Details
- Frontend app:
https://webapp.example.com
- Backend API:
https://backend.example.com
- Using reverse proxy for routing
The Problem
When my frontend tries to authenticate with the backend, I get this CORS error:
Access to fetch has been blocked by CORS policy: Request header ‘access-control-allow-origin’ is not allowed by Access-Control-Allow-Headers in preflight response
Django Configuration
I’ve installed the cors package and set up my Django settings like this:
INSTALLED_APPS = [
'expenses',
'rest_framework',
'rest_framework.authtoken',
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
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_ALLOWED_ORIGINS = [
'https://webapp.example.com',
]
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_HEADERS = [
'accept',
'authorization',
'content-type',
'origin',
'user-agent',
'x-csrftoken',
]
Frontend Request
const apiClient = axios.create({
baseURL: backendUrl,
withCredentials: true,
});
const result = await apiClient.post('/auth/login/', {
email: userEmail,
password: userPassword,
}, {
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
});
I’ve been stuck on this for a while now. Has anyone dealt with similar cross-origin authentication problems? Any help would be appreciated!