javascript - 获取发送到 Python/Django 的 POST 请求的 None 值(通过 Axios 库)

标签 javascript python django http-post axios

我正在使用 Django/Python 构建一个网络应用程序,并尝试使用 Axios 库(在 Vue.js 代码中)通过 POST 请求将数据发送到 Controller 。

POST QueryDict 似乎是空的,我不明白为什么会这样:

changeCountry: function(e, id){
  console.log("Let's change the country")
  console.log(e.target.value) // is printing correctly
  console.log(id) // also printing correctly

  axios({
    method: 'post',
    url: '/template/country',
    data: {
      id: id,
      country: e.target.value
    },
    headers: {
      'X-CSRFToken': "{{csrf_token}}"
      }
    })
    .then(function (response) {
      alert(response.data); // this is returning what I expect
    })
    .catch(function (error) {
      console.log(error);
    })
  },

Python 方法如下所示:

def update_template_country(request):

  pprint(request.POST) # prints an empty QueryDict

  id = request.POST.get('id')
  country = request.POST.get('country')

  print(id, country) #prints None None

  return HttpResponse("The country is changed") # this is being returned back to the client

顶部的 console.log 消息打印出了我的预期,并且由于没有错误,我假设 CSRF header token 没有问题。我是否遗漏了一些明显的东西或误解了它的工作原理?

编辑:查看 Chrome 网络选项卡,数据似乎已正确“发布”:

它显示了这个:

{"id":"593ff2270098e6e8d3292b60","country":"US"} 

这正是我所期望的,所以我怀疑问题出在 Django 上。但我看不出那可能是什么。

最佳答案

像这样写你的 python POST 请求:

def update_template_country(request):
  data = json.loads(request.body)
  id = data["id"]
  country = data["country"]
  '''Any other function you want to perform'''
  return HttpResponse(json.dumps({'message':'The country is changed'},status=200)

基本上问题出在 POST 请求的格式上,Django 无法正确解析它,这就是为什么当您打印 POST 请求时它返回一个空字典。

关于javascript - 获取发送到 Python/Django 的 POST 请求的 None 值(通过 Axios 库),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57014579/

相关文章:

javascript - AngularJS 中的全局 "App" Controller

python - Django 加权百分比

python - 尝试更新单个 Django 表单/模型字段失败,因为未提供用户 ID(外键)

javascript - CSS 突出显示选定的按钮

javascript - 当我向该字符串末尾添加多个字符时,为什么我一无所获?

Javascript - 如何使用点击事件和类删除 DOM 元素?

with 语句中的 Python 交互式 REPL

python - 使用 lxml 和 xpath 从 python ElementTree 中提取多个值

django - 如何使用 Flex 访问 Django 中的外键字段?

python - Django Web 应用程序的棘手编码逻辑