CORS errors in Django REST API - complete fix
Answered
39
I'm getting CORS errors when my frontend tries to access my Django REST API. "Access-Control-Allow-Origin" header is missing.
P
Asked by
python_dev
Platinum
•
447 rep
1 Answer
22
CORS issues are common in API development. Here's the complete solution:
Install django-cors-headers
pip install django-cors-headers
Configure settings.py
INSTALLED_APPS = [
...
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # Must be first
'django.middleware.common.CommonMiddleware',
...
]
# Allow specific origins
CORS_ALLOWED_ORIGINS = [
"http://localhost:3000",
"https://yourdomain.com",
]
# Or allow all (development only)
CORS_ALLOW_ALL_ORIGINS = True # Not recommended for production
F
Silver
•
169 rep
Your Answer
You need to be logged in to answer questions.
Log In to Answer