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

使用JS Fetch API向Django发POST请求时request.POST为空的原因

问题:为何Django的request.POST为空,但request.body有JSON数据?

我尝试通过JavaScript向Django服务器发送数据,前端代码如下:

let url = play_selected.dataset.url;
const csrf_token = getCookie('csrftoken');

let data = JSON.stringify( { selects: arr } );
console.log(data);
const response = await fetch(url, {
  method: 'POST', // Specify the HTTP method
  body: data, // JSON.stringify(data), // Convert data to JSON string (if object)
  headers: {
    'Content-Type': 'application/json', // Set content type header
    'X-CSRFtoken': csrf_token
  }
});
data = await response.json();
console.log(data);

selects数组是一组数字,后端调试时打印request.POST始终为空,但request.body有内容:

(Pdb) p request.POST
<QueryDict: {}>
(Pdb) p request.body
b'{"selects":["29"]}'

我认为request.POST应该显示和request.body类似的内容,请问为何request.POST为空?


原因与解决办法
  • 核心原因:Django的request.POST仅会解析Content-Type为application/x-www-form-urlencoded(表单默认编码)或multipart/form-data的请求数据。你当前发送的请求Content-Type是application/json,这类数据Django不会自动解析到request.POST中,只会保留在request.body里。

  • 解决办法1:手动解析request.body(推荐)
    在后端视图中直接解析JSON格式的请求体:

    import json
    from django.http import JsonResponse
    
    def your_view(request):
        if request.method == 'POST':
            # 解析JSON数据
            request_data = json.loads(request.body)
            selects = request_data.get('selects')
            # 编写你的业务处理逻辑
            return JsonResponse({'status': 'success', 'received_selects': selects})
    
  • 解决办法2:修改前端请求格式(适合表单类简单数据)
    如果希望数据进入request.POST,可以将数据转为表单格式发送,同时移除Content-Type设置(浏览器会自动处理为multipart/form-data):

    const formData = new FormData();
    // 循环将数组元素添加到FormData
    arr.forEach(item => formData.append('selects', item));
    
    const response = await fetch(url, {
      method: 'POST',
      body: formData,
      headers: {
        'X-CSRFtoken': csrf_token
      }
    });
    

    这种方式更适合简单的表单数据,若你的数据结构复杂,优先选择第一种JSON解析的方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 05:12:10