Django跨域

步骤 1:安装 django-cors-headers

python 复制代码
pip install django-cors-headers

步骤 2:修改 Django 配置

settings.py 中添加:

python 复制代码
INSTALLED_APPS = [
    ...,
    "corsheaders",  # 新增
]

MIDDLEWARE = [
    ...,
    "corsheaders.middleware.CorsMiddleware",  # 尽量放顶部
    ...,
]

# 允许所有域名跨域(开发环境)
CORS_ALLOW_ALL_ORIGINS = True

# 或指定前端域名(生产环境)
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
    "http://127.0.0.1:3000",
]

重启 Django 服务

python 复制代码
python manage.py runserver