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

使用Javascript Fetch向Django发POST请求时JSON解码错误求助

解决Django接收Fetch请求时的JSONDecodeError问题

我尝试用JavaScript的Fetch向Django后端发送数据,一直遇到错误:json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)。

虽然后端的两个print()语句都能输出有效的Fetch数据,但错误还是出在data_of_post = json.loads(request.body)这一行。

前端index.js代码:

fetch('save_user_post/', {
    method: 'POST',
    credentials: 'same-origin',
    headers:{
        'Accept': 'application/json',
        'X-CSRFToken': user_post_form_csrf.value,
    },
    body: JSON.stringify({
        'input_user_post_value': input_user_post.value,
    }) 
})
.then(response => response.json())
.then(user_post_save_result => {
    console.log(user_post_save_result )
})

后端views.py代码:

def save_user_post(request):
    if request.method != "POST":
            return JsonResponse({"error": "no POST method"}, status=400)
    if request.user.is_authenticated:
        print(request.body) # 这里检查是否能接收数据
        data_of_post = json.loads(request.body)
        input_user_post_value = data_of_post.get('input_user_post_value', '')
        print(f'input_user_post_value is {input_user_post_value}') # 这里检查是否能获取对应值
        post_save_result = {'post_saved_or_not': 'saved'}
        return JsonResponse(post_save_result)

问题原因

request.body是一次性的字节流对象,当你用print(request.body)读取它之后,这个流就被消耗完毕了,后续再调用json.loads(request.body)时,拿到的就是空内容,因此触发JSON解析错误。

解决步骤

  1. 先缓存request.body的内容
    修改后端代码,先把request.body赋值给一个变量,再对这个变量进行打印和JSON解析操作:

    def save_user_post(request):
        if request.method != "POST":
                return JsonResponse({"error": "no POST method"}, status=400)
        if request.user.is_authenticated:
            body_content = request.body  # 先缓存字节流内容
            print(body_content)
            data_of_post = json.loads(body_content)
            input_user_post_value = data_of_post.get('input_user_post_value', '')
            print(f'input_user_post_value is {input_user_post_value}')
            post_save_result = {'post_saved_or_not': 'saved'}
            return JsonResponse(post_save_result)
    
  2. 添加Content-Type请求头(可选但推荐)
    在Fetch的headers里添加Content-Type: application/json,明确告诉后端请求体是JSON格式,让请求更规范:

    fetch('save_user_post/', {
        method: 'POST',
        credentials: 'same-origin',
        headers:{
            'Accept': 'application/json',
            'Content-Type': 'application/json', // 添加这一行
            'X-CSRFToken': user_post_form_csrf.value,
        },
        body: JSON.stringify({
            'input_user_post_value': input_user_post.value,
        }) 
    })
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 02:20:36