Skip to content

Q&A · Answered

CORS errors in Django REST API - complete fix

asked 9 months, 2 weeks ago 2151 views 1 answer
39

I'm getting CORS errors when my frontend tries to access my Django REST API. "Access-Control-Allow-Origin" header is missing.

1 Answer

One accepted
22

Accepted answer

Not confirmed since it was written, 9 months, 2 weeks ago

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

Your answer

Say what you tried, not only what worked — the next person needs the reasoning. Code goes in a fenced block.

Shown beside your answer and never checked, so it cannot be a name someone already has here.

No account needed to answer. Sign in instead and it carries your name and earns reputation.