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

Django生产环境CORS配置失效问题求助

Django + React 跨域CORS生产环境失效排查方案

问题背景

后端基于Django、前端基于React的聊天应用分别部署在Vercel不同域名下,本地环境CORS配置正常,但生产环境请求触发以下错误:

Access to fetch at 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app/auth/sendotp/' from origin 'https://texter-frontend.vercel.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

后端CORS配置:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ALLOWED_HOSTS = ['.vercel.app'] 

CORS_ALLOW_CREDENTIALS = True
CORS_ALLOWED_ORIGINS = ['https://texter-frontend.vercel.app',]

前端请求示例:

const backendServerEndpoint = 'https://texter-backend-jp24ejwc8-sourav-pys-projects.vercel.app';
const requestData = {
    'phoneNumber' : phoneNumber
};

fetch(backendServerEndpoint + '/auth/sendotp/',{
    method: "POST",
    mode: "cors",
    credentials: 'include',
    headers: {
        "Content-Type": "application/json",        
    },
    body: JSON.stringify(requestData), 
})
// ...后续处理逻辑

排查与解决方案

1. 验证Vercel环境下Django配置加载有效性

Vercel部署时,硬编码配置可能因环境变动失效,建议通过环境变量传递关键配置:

  • 在Vercel后端项目的环境变量中添加:
    • ALLOWED_HOSTS=.vercel.app
    • CORS_ALLOWED_ORIGINS=https://texter-frontend.vercel.app
  • 修改Django settings.py,从环境变量读取配置:
    import os
    ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(",")
    CORS_ALLOWED_ORIGINS = os.environ.get("CORS_ALLOWED_ORIGINS", "").split(",")
    
  • 重新部署后端,确保环境变量生效。

2. 确认CORS依赖与中间件配置

你的中间件顺序符合要求(CorsMiddleware需在CommonMiddleware之前),但需补充检查:

  • 确保安装最新版django-cors-headers:执行 pip install --upgrade django-cors-headers,旧版本可能存在Vercel适配问题。
  • 确认INSTALLED_APPS中已添加corsheaders:
    INSTALLED_APPS = [
        # ...其他应用
        'corsheaders',
    ]
    

3. 临时排查域名匹配问题

临时将CORS_ALLOW_ALL_ORIGINS设为True(仅用于排查,生产环境禁用):

CORS_ALLOW_ALL_ORIGINS = True

重新部署后测试:

  • 若请求正常,说明原CORS_ALLOWED_ORIGINS中的域名存在拼写错误、协议不匹配(如前端实际用http而非https),或Vercel前端域名有变动(如预览域名与正式域名不一致)。
  • 若仍报错,说明CORS配置未被加载,需检查Django settings在Vercel环境中的生效情况。

4. 检查Vercel部署配置

查看后端项目的vercel.json,确保正确指定Django入口与settings:

{
  "builds": [
    {
      "src": "texter_backend/wsgi.py",
      "use": "@vercel/python",
      "config": { "maxLambdaSize": "15mb", "runtime": "python3.10" }
    }
  ],
  "routes": [
    {
      "src": "/(.*)",
      "dest": "texter_backend/wsgi.py"
    }
  ]
}

同时确认wsgi.py中正确加载settings:

import os
from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'texter_backend.settings')
application = get_wsgi_application()

5. 验证响应头

在浏览器Network面板查看请求的响应头:

  • 若Access-Control-Allow-Origin不存在,说明后端未正确返回CORS头,需回到配置加载环节排查。
  • 若存在但仍报错,确认CORS_ALLOW_CREDENTIALS = True与前端credentials: 'include'的配置匹配(你的当前配置符合要求,此为兜底排查)。

内容的提问来源于stack exchange,提问作者Sourav Singh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 04:55:08