Fix CORS Error: Access to XMLHttpRequest at 'https://api.example.com/data/' from origin 'https://app.example.com' has been blocked by CORS policy. in Django
This error means the browser blocked a cross-origin request because the Django backend did not include the correct CORS headers. Fix it by installing django-cors-headers, adding it to INSTALLED_APPS and MIDDLEWARE, and configuring CORS_ALLOWED_ORIGINS with the frontend's domain in settings.py.
Reading the Stack Trace
Here's what each line means:
- has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.: The browser sent a preflight OPTIONS request and the Django server did not respond with the required Access-Control-Allow-Origin header.
- Request Method: OPTIONS: Browsers send an OPTIONS preflight request for cross-origin POST/PUT/DELETE requests to check if the server allows them.
- "OPTIONS /data/ HTTP/1.1" 403 0: Django returned 403 for the preflight because no CORS middleware is installed to handle OPTIONS requests.
Common Causes
1. django-cors-headers not installed
The django-cors-headers package is not installed or not configured, so Django does not add CORS response headers.
# settings.py — no CORS configuration
INSTALLED_APPS = [
'django.contrib.admin',
'rest_framework',
# Missing: 'corsheaders'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
# Missing: 'corsheaders.middleware.CorsMiddleware'
]
2. CORS middleware in wrong position
CorsMiddleware is placed after CommonMiddleware, so it does not process the response before other middleware blocks it.
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
'corsheaders.middleware.CorsMiddleware', # Too late in the chain
]
3. Frontend origin not in allowed list
The frontend domain is not included in CORS_ALLOWED_ORIGINS, so the CORS middleware rejects it.
# settings.py
CORS_ALLOWED_ORIGINS = [
'https://old-frontend.example.com', # New frontend not listed
]
The Fix
Install django-cors-headers and add CorsMiddleware before CommonMiddleware in MIDDLEWARE. List all allowed frontend origins in CORS_ALLOWED_ORIGINS. Never use CORS_ALLOW_ALL_ORIGINS = True in production as it allows any website to make requests to your API.
# settings.py — no CORS configuration
INSTALLED_APPS = [
'django.contrib.admin',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.middleware.common.CommonMiddleware',
]
# pip install django-cors-headers
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'corsheaders', # Added
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'corsheaders.middleware.CorsMiddleware', # Must be before CommonMiddleware
'django.middleware.common.CommonMiddleware',
]
CORS_ALLOWED_ORIGINS = [
'https://app.example.com',
'http://localhost:3000', # Development
]
# Optional: allow specific headers and methods
CORS_ALLOW_HEADERS = [
'accept',
'authorization',
'content-type',
'x-csrftoken',
]
CORS_ALLOW_METHODS = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE',
'OPTIONS',
]
Testing the Fix
import pytest
from django.test import TestCase, Client
class TestCORSHeaders(TestCase):
def test_cors_headers_on_allowed_origin(self):
response = self.client.options(
'/api/data/',
HTTP_ORIGIN='https://app.example.com',
HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET',
)
assert response.get('Access-Control-Allow-Origin') == 'https://app.example.com'
def test_cors_headers_missing_for_disallowed_origin(self):
response = self.client.options(
'/api/data/',
HTTP_ORIGIN='https://evil.example.com',
HTTP_ACCESS_CONTROL_REQUEST_METHOD='GET',
)
assert response.get('Access-Control-Allow-Origin') is None
def test_preflight_returns_200(self):
response = self.client.options(
'/api/data/',
HTTP_ORIGIN='https://app.example.com',
HTTP_ACCESS_CONTROL_REQUEST_METHOD='POST',
HTTP_ACCESS_CONTROL_REQUEST_HEADERS='content-type',
)
assert response.status_code == 200
def test_get_request_includes_cors_header(self):
response = self.client.get(
'/api/data/',
HTTP_ORIGIN='https://app.example.com',
)
assert response.get('Access-Control-Allow-Origin') == 'https://app.example.com'
Run your tests:
pytest
Pushing Through CI/CD
git checkout -b fix/cors-headers-config,git add settings.py requirements.txt,git commit -m "fix: install and configure django-cors-headers for frontend access",git push origin fix/cors-headers-config
Your CI config should look something like this:
name: CI
on:
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
- run: pip install -r requirements.txt
- run: pytest --tb=short -q
The Full Manual Process: 18 Steps
Here's every step you just went through to fix this one bug:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- Monitor production to confirm the error is resolved
Total time: 30-60 minutes. For one bug.
Or Let bugstack Fix It in Under 2 minutes
Every step above? bugstack does it automatically.
Step 1: Install the SDK
pip install bugstack
Step 2: Initialize
import bugstack
bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])
Step 3: There is no step 3.
bugstack handles everything from here:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- Deploys to production (or opens a PR for review)
Time from error to fix deployed: Under 2 minutes.
Human involvement: zero.
Try bugstack Free →No credit card. 5-minute setup. Cancel anytime.
Deploying the Fix (Manual Path)
- Run the full test suite locally including CORS header tests.
- Open a pull request with the CORS configuration changes.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- Merge to main and verify cross-origin requests work in staging.
Frequently Asked Questions
BugStack runs the fix through your existing test suite, generates tests for both allowed and disallowed origins, and validates that preflight requests succeed before marking it safe to deploy.
BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.
No. It allows any website to make authenticated requests to your API. Only use it in development. In production, always list specific allowed origins.
POST requests with JSON content type trigger a preflight OPTIONS request. Ensure CorsMiddleware handles OPTIONS and that your allowed headers include 'content-type'.