首页 > 解决方案 > Sending a POST request through Javascript on Django - failed to retrieve data

问题描述

I'm trying to send a POST request to my Django view using plain javascript (I don't want any unnecessary libraries involved). The data is not sent through a form, but by using fetch. For now I just want to be able to manipulate the request.POSTin my views.py, nothing more.

Here's my code:
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})

The request is sent, the csrftoken is received correctly, but the request.POST returns just <QueryDict: {}>, instead of what I'm expecting (headers, data...).

I've searched and found a lot of similar questions, the most similar one being this one, but still I can't seem to find a solution.

Any idea?

标签: javascriptpythondjango

解决方案


尝试将“内容类型”添加到fetch调用中的标头(而不是 dataType 参数),并将数据参数更改为带有字符串化对象的正文:

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

推荐阅读