Django REST Framework API跨域问题:已装django-cors-headers仍报错
Hey there, it looks like you’ve already checked the first box by installing django-cors-headers, but you’re missing a couple critical setup steps to get it working properly. Let’s walk through the full configuration process:
1. Add the Cors Middleware to Your Project
You’ve added corsheaders to INSTALLED_APPS, but the middleware is what actually handles the cross-origin requests. Important: Place this middleware before django.middleware.common.CommonMiddleware in your MIDDLEWARE list—order matters here:
MIDDLEWARE = [ 'django.contrib.admin.middleware.AdminSiteMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'corsheaders.middleware.CorsMiddleware', # Add this line first 'django.middleware.common.CommonMiddleware', # ... rest of your existing middleware entries ]
2. Configure Allowed Origins
Next, you need to define which domains are allowed to access your API. Choose one of these options based on your environment:
Option A: Allow Specific Trusted Origins (Recommended for Production)
List exact, trusted domains in your settings.py to keep your API secure:
CORS_ALLOWED_ORIGINS = [ "https://your-production-frontend.com", "http://localhost:3000", # Common for local React/Vue development "http://127.0.0.1:5173", ]
Option B: Allow All Origins (Only for Local Development)
If you’re testing locally and want to skip origin restrictions temporarily, add this (never use this in production):
CORS_ALLOW_ALL_ORIGINS = True
3. Optional: Tweak Advanced CORS Settings
Depending on your API’s needs, you can customize additional rules like allowed HTTP methods, headers, or cookie support:
# Allow specific HTTP methods CORS_ALLOW_METHODS = [ "DELETE", "GET", "OPTIONS", "PATCH", "POST", "PUT", ] # Allow custom request headers CORS_ALLOW_HEADERS = [ "accept", "authorization", "content-type", "x-csrftoken", "x-requested-with", ] # Enable cookie support for cross-origin requests (if your API uses sessions/auth) CORS_ALLOW_CREDENTIALS = True
Quick Note on the Pip Upgrade Prompt
The message about upgrading pip from 9.0.1 to 9.0.3 is just a friendly recommendation—it won’t impact your CORS issue. If you want to upgrade anyway, run:
pip install --upgrade pip
Once you’ve added these configurations, restart your Django server. Your cross-origin error should be gone!
内容的提问来源于stack exchange,提问作者zennn

