Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

How do you handle CORS (Cross-Origin Resource Sharing) in Django REST Framework? Django REST Framework में CORS कैसे handle करते हैं?

Answer

CORS allows APIs to be accessed from different domains. Use django-cors-headers middleware to enable CORS. Configure allowed origins, methods, and headers in settings to allow cross-origin requests securely.

// Install django-cors-headers
pip install django-cors-headers

// settings.py
INSTALLED_APPS = [
    'corsheaders',
    'django.contrib.admin',
    'rest_framework',
]

MIDDLEWARE = [
    'corsheaders.middleware.CorsMiddleware',  # Must be early in the list
    'django.middleware.common.CommonMiddleware',
    # ... other middleware
]

// Allow all origins (Development only)
CORS_ALLOW_ALL_ORIGINS = True

// Allow specific origins (Production)
CORS_ALLOWED_ORIGINS = [
    'http://localhost:3000',
    'http://localhost:8080',
    'https://example.com',
    'https://www.example.com',
]

// Allow credentials (cookies, auth headers)
CORS_ALLOW_CREDENTIALS = True

// Allowed methods
CORS_ALLOW_METHODS = [
    'GET',
    'POST',
    'PUT',
    'PATCH',
    'DELETE',
    'OPTIONS',
]

// Allowed headers
CORS_ALLOW_HEADERS = [
    'accept',
    'accept-encoding',
    'authorization',
    'content-type',
    'dnt',
    'origin',
    'user-agent',
    'x-csrftoken',
    'x-requested-with',
]

// Advanced CORS Configuration
CORS_ALLOWED_ORIGIN_REGEXES = [
    r'^https://\w+\.example\.com$',  # Allow any subdomain
]

CORS_EXPOSE_HEADERS = ['X-Total-Count']  # Expose custom headers
CORS_MAX_AGE = 3600  # Preflight cache duration

// Per-View CORS Configuration
from corsheaders.decorators import ensure_csrf_cookie

@ensure_csrf_cookie
def get_csrf_token(request):
    return JsonResponse({'csrfToken': get_token(request)})

// Test CORS
# Frontend JavaScript
fetch('http://localhost:8000/api/books/', {
    method: 'GET',
    headers: {
        'Authorization': 'Token abc123',
        'Content-Type': 'application/json',
    }
})
.then(response => response.json())
.catch(error => console.error('CORS Error:', error));

// CORS Errors to Handle
// Access-Control-Allow-Origin header missing
// Credentials mode is 'include' but... not allowed
// Method not allowed by CORS policy
// Headers not allowed by CORS policy

django-cors-headers use करें CORS enable करने के लिए। Allowed origins, methods, headers configure करें। Development में सभी origins allow कर सकते हो, production में specific करो।

Was this answer clear?