Django不会从fetch()中提取数据

问题描述 投票:0回答:2

我正在使用fetch()来对我的服务器进行ajax调用。 request.POST返回空的QueryDict,而request.body恢复我的实际数据。我为什么做错了?!?

这是我的js代码:

fetch(url, {
            method: "post",
            credentials: 'same-origin',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-CSRFToken': csrftoken,
                'X-Requested-With': 'XMLHttpRequest'
            },
            body: JSON.stringify(data)
        })
            .then(async res => ({
                status: res.status,
                body: await res.json(),
                isOk: res.ok
            }))
javascript django ajax fetch-api
2个回答
0
投票

我认为您的问题已包含在the docs中:基本上POST only包含表单数据。文件和其他非格式数据分别位于FILE和body属性中。


0
投票

request.POST用于表单数据。但是,您不是在发送表单数据。您正在发送JSON。因此没有QueryDict,并且request.POST正确保持为空。

© www.soinside.com 2019 - 2024. All rights reserved.