Django Rest Framework指定跨域源无效,全局允许则正常问题求助
解决Django Rest Framework跨域请求拦截问题
问题分析
你遇到的核心问题是:前端部署在http://localhost:3000,请求后端127.0.0.1:8000时,配置CORS_ALLOWED_ORIGINS = ["http://localhost:3000"]无效,但CORS_ORIGIN_ALLOW_ALL = True可以正常请求。这通常是因为CORS中间件配置顺序错误,或者django-cors-headers未正确初始化导致的。
解决方案
1. 确保django-cors-headers正确安装与配置
首先确认已安装依赖包:
pip install django-cors-headers
在settings.py中完成以下配置:
- 将
corsheaders加入INSTALLED_APPS:
INSTALLED_APPS = [ # 其他应用 'corsheaders', 'rest_framework', # 你的自定义应用 ]
- 将
CorsMiddleware放在CommonMiddleware之前(顺序错误会导致CORS头不生效,这是关键):
MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # 其他中间件 ]
2. 正确配置CORS_ALLOWED_ORIGINS
确保配置的源和前端实际请求源完全一致(包含协议、域名、端口):
CORS_ALLOWED_ORIGINS = [ "http://localhost:3000", ]
3. 额外检查项
- 确认后端
ALLOWED_HOSTS包含127.0.0.1或localhost:
ALLOWED_HOSTS = ['127.0.0.1', 'localhost']
- 可尝试将前端请求的后端地址改为
http://localhost:8000(与前端域名一致,避免浏览器将localhost和127.0.0.1视为不同源的潜在问题):
useEffect(() => { fetch("http://localhost:8000/api/articles/", { method: "GET", headers: { 'Content-Type': 'application/json', 'Authorization': 'Token 746a97c3f72a5fc388762c5732e2c8340fc75ba9', } }) .then(res => res.json()) .then((data) => setArticles(data)) .catch((error) => console.log(error)) }, []);
验证
完成上述配置后,重启Django服务,重新发起请求,跨域拦截问题应能解决。
内容的提问来源于stack exchange,提问作者Ryan
相关产品推荐
相关产品推荐

