如何使用Axios发布到Django? [英] How do I post to Django using Axios?

查看:142
本文介绍了如何使用Axios发布到Django?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我使用ReactJS,所以我正在从Jquery AJAX迁移到Axios,所以我认为它更干净,在将简单的请求发布到服务器时遇到了一些麻烦,post方法遍历我的视图,但是每当我print(request.POST)我有一个空的查询集(< QueryDict:{}> ).

I'm moving from Jquery AJAX to Axios since I'm using ReactJS so I think it's cleaner, I am having some troubles posting a simple request to the server, the post method goes through my view but whenever I print(request.POST) I have an empty queryset (<QueryDict: {}>).

这是JS:

axios({
  method: 'post',
  url: SITE_DOMAIN_NAME + '/my_url_name/', #http://127.0.0.1:8000/my_url_name
  data: {
    'tes1':'test',
    'tes2':'test'
  },
  headers: {
    "X-CSRFToken": CSRF_TOKEN, 
    "content-type": "application/json" #tried without content-type too.
  }
}).then(function (response) {
  console.log(response)
}).catch(function (error) {
  console.log(error)
});

Django视图是一个简单的ClassBasedView.

Django view is a simple ClassBasedView.

我在做什么错了?

推荐答案

request.POST 仅适用于表单编码的数据.如果要发布JSON,则应改用 request.body .

request.POST is only for form-encoded data. If you are posting JSON, then you should use request.body instead.

import json
json.loads(request.body.decode('utf-8'))

如果这样做,则必须对基于类的视图进行更改,以改为使用 request.body .

If you do this, you'll have to make changes to your class based view to use request.body instead.

如果您想让axios发送表单编码数据,请在此问题上GitHub可能会有所帮助.

If you want to get axios to send form encoded data instead, this issue on GitHub might help.

这篇关于如何使用Axios发布到Django?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆