Django+React跨域异常:配置django-cors-headers仍报跨域头缺失错误
Troubleshooting CORS Error Between Django REST Framework and React
Hey there, let’s work through this CORS issue step by step—since Postman can hit your API just fine but React can’t, the problem is almost certainly a small misconfiguration that’s easy to fix. Here’s what to check:
1. Verify Your DRF CORS Middleware Setup
First, let’s make sure your Django backend is actually sending the correct CORS headers. Even if you added the settings, small missteps can break things:
- Check Middleware Order: The
CorsMiddlewareneeds to run beforeCommonMiddlewarein yourMIDDLEWARElist. Middleware executes top-to-bottom, so if it’s placed later, it won’t get a chance to add the CORS headers before the response is sent. Yoursettings.pyshould look like this:MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # Your other middleware (SecurityMiddleware, SessionMiddleware, etc.) ] - Double-Check CORS Settings: Ensure
CORS_ALLOW_ALL_ORIGINS = Trueis spelled correctly (Django settings are case-sensitive—no lowercase here!). Also confirmcorsheadersis in yourINSTALLED_APPS:INSTALLED_APPS = [ # Default apps... 'corsheaders', # Your custom apps... ] - Restart Your Django Server: Any changes to
settings.pyor middleware require a server restart to take effect. Even if you think you did it, give it another shot—this is a super common oversight!
2. Inspect Your React Axios Request
Next, let’s rule out frontend issues:
- Confirm the Request URL: Make sure your axios call is using the exact same URL that worked in Postman. For example:
If you’re usingimport axios from 'axios'; const fetchCategories = async () => { try { const response = await axios.get('http://127.0.0.1:8000/categories/'); console.log(response.data); } catch (error) { console.error('Error fetching categories:', error); } };localhost:8000instead of127.0.0.1:8000, while they point to the same local server, browsers treat them as different origins—but since you setCORS_ALLOW_ALL_ORIGINS = True, this shouldn’t matter. Still, matching the Postman URL exactly eliminates variables. - Check for Axios Interceptors: If you’ve added any axios interceptors (to add auth tokens, for example), make sure they aren’t accidentally modifying or removing headers that affect CORS. Temporarily comment out interceptors to test if that fixes the issue.
- Use Browser DevTools: Open your browser’s Network tab, send the request, and look at the Response Headers. If you don’t see
Access-Control-Allow-Origin: *, that confirms the backend isn’t sending the header (so go back to step 1). If you do see it, the issue might be a browser cache—check the "Disable cache" box in DevTools and re-run the request.
3. Edge Cases to Consider
- CSRF Middleware: For GET requests, CSRF tokens aren’t required, but if you later switch to POST/PUT, you’ll need to handle CSRF. But since this is a GET request, this isn’t the culprit here.
- Other Security Middleware: If you’re using third-party security middleware (like
django-permissions-policyor custom middleware), ensure it isn’t overriding or stripping the CORS headers. Temporarily disable non-essential middleware to test.
Start with restarting your Django server and double-checking the middleware order—those are the most frequent fixes for this exact scenario. Let me know if any of these steps resolve your issue!
内容的提问来源于stack exchange,提问作者saran
相关产品推荐
相关产品推荐

