How do I post to Django using Axios?

自闭症网瘾萝莉.ら 提交于 2020-12-02 11:00:46

问题


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: {}>).

Here's the 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 view is a simple ClassBasedView.

What am I doing wrong?


回答1:


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'))

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

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



来源:https://stackoverflow.com/questions/49430161/how-do-i-post-to-django-using-axios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!