【问题标题】:Django receives incomplete POST dataDjango 收到不完整的 POST 数据
【发布时间】:2021-07-31 02:11:18
【问题描述】:

我将 json 格式的数据发布到使用 Django 3.1.2 编写的后端。但是,数据似乎没有正确接收。

js代码:

var httpRequest = new XMLHttpRequest();
httpRequest.open("POST", "http://" + window.location.host + "/upload/", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send(encodeURI("data=" + json));
httpRequest.onreadystatechange = function () {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
    console.log("Done!");
}

姜戈:

data = request.POST.get('data')
f = open('data.txt', 'w+')
f.write(data)
f.close()

写入文件的数据不完整。当我尝试打印它时,它也不完整。可能是什么问题?是不是因为我发的json字符串太长了?

【问题讨论】:

  • 这里是否真的缺少尾随括号:httpRequest.send(encodeURI("data=" + json); 或者是粘贴错误?
  • 粘贴错误。我的代码实际上并没有出错。唯一的问题是我无法在后端获取完整的数据。
  • 不完整是什么意思?这有点像{"key": "va
  • 发布的 json 字符串非常长,但我在后端获得的数据仅包含原始数据的前 50 个左右字符。剩下的 json 已经消失了。

标签: javascript python django


【解决方案1】:

我设法通过对我的 python 代码进行这个小改动来解决这个问题:

# data = request.POST.get('data')
data = request.body.decode('utf-8')

尽管如此,我仍然不明白为什么这在我的情况下有效。

【讨论】:

    猜你喜欢
    • 2014-11-25
    • 2021-08-28
    • 1970-01-01
    • 2012-08-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-23
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多