Axios: Post not sending data properly

Created on 18 Aug 2016  ·  3Comments  ·  Source: axios/axios

Hello,
I have a django application where I want to make POST by clicking on <button> which is not in <form>
The problem is that data sent to view function are not being sent properly.

Here is axios code:

 axios({
        method: 'post',
        url: '/url/to/view'
        data: {
            obj_id: objectid,
            content_type: contenttype,
            like: !is_liked
        },
        xsrfCookieName: 'csrftoken',
        xsrfHeaderName: 'X-CSRFToken',
        headers: {'X-Requested-With': 'XMLHttpRequest',
                  'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
    }).then(function (response) { 
        console.log(response);
    });

and here view code:

def my_view(request):
    print request.POST
    return HttpResponse('XX')

I cannot access request.POST data because the key is entire dict and value empty list:
<QueryDict: {u'{"obj_id":"182","content_type":"video","like":true}': [u'']}>

Most helpful comment

The problem is that objects are serialized to JSON by default while you need to send the data in the `application/x-www-form-urlencoded' format. The easiest solution is to use a library like qs:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

See this comment for details.

Hope this helps!

All 3 comments

The problem is that objects are serialized to JSON by default while you need to send the data in the `application/x-www-form-urlencoded' format. The easiest solution is to use a library like qs:

var qs = require('qs');
axios.post('/foo', qs.stringify({ 'bar': 123 });

See this comment for details.

Hope this helps!

Another way is putting the values into the FormData object and post

I wrote small wrapper aroud axios which works fine with default Django >1.8 settings. Hope this helps somebody!

Was this page helpful?
0 / 5 - 0 ratings