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.
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.
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() .
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With