Django配置settings.py后仍遇CORS错误,求解决方案
Django + React 跨域CORS错误排查与解决
问题描述
前端采用React(Vite),后端采用Django。Postman调用Django接口无CORS错误且运行正常,但React发送POST请求时出现CORS错误。已做如下配置:
Django settings.py 配置
ALLOWED_HOSTS = ["*"] CORS_ORIGIN_ALLOW_ALL = True CORS_ORIGIN_WHITELIST = [ 'http://localhost:5173' ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ]
React 端配置
VITE_API_URL=http://127.0.0.1:8000/api/v1
const apiClient = axios.create({ baseURL: import.meta.env.VITE_API_URL, headers: { "Accept": "application/json", "Access-Control-Allow-Origin": "*", "X-Requested-With": "XMLHttpRequest", "Access-Control-Allow-Methods" : "GET,POST,PUT,DELETE,OPTIONS", "Access-Control-Allow-Headers": "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" } }); const register = (data: any) => apiClient.post('/user/register/', data)
解决步骤
1. 修正Django CORS配置冲突
CORS_ORIGIN_ALLOW_ALL = True 和 CORS_ORIGIN_WHITELIST 同时设置会产生冲突,Django会优先遵循更严格的规则。二选一即可:
- 若允许所有开发来源,保留
CORS_ORIGIN_ALLOW_ALL = True,删除CORS_ORIGIN_WHITELIST配置 - 若需精确控制来源,删除
CORS_ORIGIN_ALLOW_ALL = True,确保白名单完全匹配React运行地址(注意localhost:5173与127.0.0.1:5173属于不同来源)
2. 移除React请求头中无效的CORS字段
Access-Control-Allow-Origin、Access-Control-Allow-Methods、Access-Control-Allow-Headers是后端响应头,前端发送这些字段会触发浏览器预检请求失败。修改React的axios配置:
const apiClient = axios.create({ baseURL: import.meta.env.VITE_API_URL, headers: { "Accept": "application/json", "X-Requested-With": "XMLHttpRequest", "Content-Type": "application/json" // 发送JSON数据时需添加该字段 } });
3. 确保Django正确安装并启用corsheaders中间件
- 确认已安装依赖:
pip install django-cors-headers - 在
settings.py的INSTALLED_APPS中添加corsheaders:INSTALLED_APPS = [ # ... 其他应用 'corsheaders', ] - 在
MIDDLEWARE中添加corsheaders.middleware.CorsMiddleware,必须放在django.middleware.common.CommonMiddleware之前:MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', # ... 其他中间件 ]
4. 校验前后端地址一致性
确保React运行地址与Django配置的白名单完全匹配,同时VITE_API_URL指向的后端地址可正常访问(比如localhost:8000与127.0.0.1:8000格式统一)。
5. 确认OPTIONS预检请求被正确处理
CORS_ALLOW_METHODS已包含OPTIONS,只要中间件顺序正确,django-cors-headers会自动处理OPTIONS预检请求,无需额外编写视图逻辑。
内容的提问来源于stack exchange,提问作者blue water
相关产品推荐
相关产品推荐

