Search code examples
djangoreactjsdjango-rest-frameworkcreate-react-app

CORS issue with react and django-rest-framework


I'm using react on the frontend side and Django on the backend. I using django-cors-headers for managing CORS in my Django app.

I have added the package in INSTALLED_APPS like this:-

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework.authtoken',
    'rest_framework',
    'corsheaders',
    'services',
    'feeds',
    'knox',
    'users',
] 

then I have also added same in MIDDLEWARE

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',
    'django.middleware.common.CommonMiddleware',
]

CORS_ALLOW_CREDENTIALS = True
CORS_ORIGIN_ALLOW_ALL = True
ALLOWED_HOSTS = ['*']

and I'm passing CORS headers from my client-side React app like:-

const Axios = axios.create({
    baseURL: `${BASE_URL}/api`,
    timeout: 1000,

    headers: { 
        'X-Custom-Header': 'foobar', 
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*'
     }  
})

Error on frontend:-

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/register' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.

Solution

  • there was a bug in my client-side headers'X-Custom-Header': 'foobar', after removing it started working fine