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

Django CORS报错:请求头responsetype不被允许的解决咨询

解决方案:Django CORS 允许 responsetype 请求头并支持 Blob 下载

1. 修复 CORS 配置问题

预检错误的核心原因是Django corsheaders的CORS_ALLOW_HEADERS未正确包含小写的responsetype字段。直接添加该字段时需注意不要覆盖默认允许的请求头,否则会导致Content-Type等必要字段被拦截,这是常见的配置误区。正确配置方式如下:

在main/settings.py中添加:

from corsheaders.defaults import default_headers

# 继承默认允许的请求头,同时追加自定义的responsetype字段
CORS_ALLOW_HEADERS = default_headers + (
    'responsetype',
)

2. 修正 API 代码中的两处错误

你的API代码存在两个影响下载功能的小问题:

  • content_type拼写错误:多了一个冗余的f,应改为"application/octet-stream"
  • 文件名重复添加.csv后缀:filename变量已包含后缀,无需再次拼接

修正后的API代码:

@api_view(["POST"])
def downloadCSV(request):
    request_body = request.data
    response = HttpResponse(
        some_service.call_some_other_service(),
        content_type="application/octet-stream",  # 修正拼写错误
    )
    today = datetime.today().strftime("%Y-%m-%d")
    filename = f"{today}_Data.csv"
    response["Content-Disposition"] = f'attachment; filename="{filename}"'  # 移除重复的.csv后缀
    return response

3. 前端请求修正

你提到的responseType = bob应为笔误,正确的响应类型是blob。确保前端请求时配置对应参数:

// Axios 请求示例
axios.post('/resource1/downloadCSV', requestData, {
  responseType: 'blob',  // 修正为正确的blob类型
  headers: {
    'responsetype': 'blob'  // 与后端允许的请求头字段匹配
  }
}).then(res => {
  // 处理Blob文件下载逻辑
  const url = window.URL.createObjectURL(new Blob([res.data]));
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute('download', res.headers['content-disposition'].match(/filename="(.+)"/)[1]);
  document.body.appendChild(link);
  link.click();
  link.remove();
  window.URL.revokeObjectURL(url);
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 20:40:18