Django配置django-cors-headers后仍遇CORS跨域拦截问题求助
Django CORS跨域拦截问题排查
问题描述
出现跨域拦截错误:
Access to fetch at 'http://127.0.0.1:8000/api/movie/1' from origin 'http://localhost:3000' has been blocked by CORS policy
已按django-cors-headers官方文档完成配置,尝试多种方案仍未解决,以下是项目settings.py配置文件:
from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', "rest_framework", "cinemagic", ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'cinemagic_backend.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'cinemagic_backend.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'djongo', 'NAME': "cinemagic", } } AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_TZ = True STATIC_URL = 'static/' DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ]
排查方向
- 域名严格匹配问题:尽管
localhost和127.0.0.1指向同一IP,但CORS对域名/IP做严格匹配。尝试在CORS_ALLOWED_ORIGINS中同时添加前端可能使用的IP形式:CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", "http://127.0.0.1:3000", ] - ALLOWED_HOSTS配置:当前
ALLOWED_HOSTS为空,在DEBUG模式下虽默认允许本地访问,但显式添加可避免潜在问题:ALLOWED_HOSTS = ['localhost', '127.0.0.1'] - 验证依赖安装:执行
pip list确认django-cors-headers已正确安装,且版本与当前Django版本兼容。 - 临时放宽限制测试:临时设置
CORS_ALLOW_ALL_ORIGINS = True(仅用于排查,生产环境禁用),若问题解决,说明是域名匹配类问题,再针对性调整CORS_ALLOWED_ORIGINS。 - 预检请求处理:若请求为OPTIONS预检请求,确保视图支持OPTIONS方法。使用DRF视图类默认会处理OPTIONS,自定义视图需手动添加支持。
- 清除浏览器缓存:浏览器可能缓存旧的CORS响应头,尝试用隐身模式或清除缓存后重新测试。
内容的提问来源于stack exchange,提问作者Sachin
相关产品推荐
相关产品推荐

