You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 CorsMiddleware needs to run before CommonMiddleware in your MIDDLEWARE list. 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. Your settings.py should 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 = True is spelled correctly (Django settings are case-sensitive—no lowercase here!). Also confirm corsheaders is in your INSTALLED_APPS:
    INSTALLED_APPS = [
        # Default apps...
        'corsheaders',
        # Your custom apps...
    ]
    
  • Restart Your Django Server: Any changes to settings.py or 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:
    import 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);
      }
    };
    
    If you’re using localhost:8000 instead of 127.0.0.1:8000, while they point to the same local server, browsers treat them as different origins—but since you set CORS_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-policy or 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:24:23