Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios POST request not working when passed object

Tags:

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.

like image 895
aslamdoctor Avatar asked Feb 17 '18 09:02

aslamdoctor


People also ask

How pass JSON object in POST request Axios?

How to Send POST JSON Requests Using Axios. The POST request is used to send data to an endpoint. For example, if we have a registration page where users submit their information, this information can be sent as JSON to the endpoint we specify using a POST JSON request.

How do I send a POST request from Axios?

A POST request can be made using Axios to “post” data to an endpoint. This endpoint may then use this POST request to perform a certain task or trigger an event. The HTTP post request is performed by calling axios. post() .


1 Answers

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().

like image 58
connexo Avatar answered Sep 23 '22 12:09

connexo