aslamdoctor
aslamdoctor

Reputation: 3935

Axios POST request not working when passed object

I am trying to do a post request in a vue js app using axios to a local API and the response is returning empty data. The post request on API is working fine using Postman tool. Below is my code

var the_data = {
    title: 'This is title',
    description: 'this is description'
}

axios.post('/api/snippets/insert', the_data)
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

On the API end, I am using a simple PHP script and printing whole $_POST request data using this code

var_dump($_POST);

But this is returning empty array.

Upvotes: 5

Views: 10450

Answers (1)

connexo
connexo

Reputation: 56720

I was running into this as well. Axios does not send the POST data in the form you're expecting. You need something like http://github.com/ljharb/qs and then use axios.post('/api/snippets/insert', Qs.stringify(the_data)). Please note this build on cdnjs uses Qs, not qs.

Alternatives to qs would be e.g. JSON.stringify() or jQuery's $.param().

Upvotes: 4

Related Questions