gpt4 book ai didi

javascript - 在 Django 上通过 Javascript 发送 POST 请求 - 检索数据失败

转载 作者:行者123 更新时间:2023-11-30 20:05:19 25 4
gpt4 key购买 nike

我正在尝试使用普通 javascript 向我的 Django View 发送 POST 请求(我不想涉及任何不必要的库)。数据不是通过表单发送的,而是使用 fetch 发送的。 .现在我只想能够操纵 request.POST在我的 views.py 中,仅此而已。

这是我的代码:
Javascript

let article = document.querySelector('article')
articleId = article.getAttribute('data-product-id')

# some other stuff
fetch("{% url 'shop:shoplist' 1 %}", {
method: 'POST',
dataType: "application/json",
data: {'article_id': articleId},
headers: {'X-CSRFToken': csrf_token}
})

python

if request.method == 'POST':
testing = request.POST
return JsonResponse({'test': testing})

请求发送后,csrftoken被正确接收,但是 request.POST只返回 <QueryDict: {}> ,而不是我所期望的( header 、数据...)。

我搜索并发现了很多类似的问题,最相似的是 this one ,但我似乎仍然找不到解决方案。

有什么想法吗?

最佳答案

尝试在 fetch 调用中将“content-type”添加到 header (而不是 dataType 参数)并将数据参数更改为带有字符串化对象的正文:

fetch("{% url 'shop:shoplist' 1 %}", { 
method: 'POST',
body: JSON.stringify({'article_id': articleId}),
headers: {
'X-CSRFToken': csrf_token,
'Content-Type': 'application/json'
}})

关于javascript - 在 Django 上通过 Javascript 发送 POST 请求 - 检索数据失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995107/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com