I'm busy testing the Axios plugin for Node.JS and I'm having some difficulty with POST Request.
For testing I have a Basic PHP script
// Identify GET Request
if(!empty($_GET)) {
$type = "Req Type : GET";
$params = $_GET;
$array = $_GET["array"];
$arrayVerify = gettype($array);
}
// Identify POST Request
if(!empty($_POST)) {
$type = "Req Type : POST";
$params = $_POST;
$array = $_POST["array"];
$arrayVerify = gettype($array);
}
$response = new stdClass();
$response->type = $type;
$response->array = $array;
$response->arrayVerify = $arrayVerify;
echo json_encode($response);
exit();
As an initial test I am using JQuery Ajax as follows
data = {};
data.array = ["One", "Two", "Three"];
$.ajax ({
url : "url_goes_here",
type : "POST",
dataType : "json",
data : data,
success : function(res) { console.log(JSON.stringify(res)); },
error : function(res) { abandonAllHope(); }
});
I get the following output
{"type":"Req Type : POST","array":["One","Two","Three"],"arrayVerify":"array"}
Which looks like well formed JSON, the array is still an array and PHP identified it as an array which is good
Then when I try with Axios from Node.js
var axios = require("axios");
var data = new URLSearchParams();
data.append("array", ["One", "Two", "Three"]);
axios ({
url : "url_goes_here",
method : "POST",
data : data
})
.then(function(res) { console.log(JSON.stringify(res.data)); })
.catch(function(res) { abandonAllHope(); });
I get the following output
{"type":"Req Type : POST","array":"One,Two,Three","arrayVerify":"string"}
The array seems to just be a concatenation of the values and PHP identified it as a string
The JQuery seemed to do what I expected but the Axios didn't, why is that? How do I tell Axios to use the data as JSON?
UPDATE
I did also try as follows
var axios = require("axios");
var data = {};
data.array = ["One", "Two", "Three"];
axios ({
url : lv_url,
method : "POST",
data : JSON.stringify(data)
})
.then(function(res) { console.log(JSON.stringify(res.data)); })
.catch(function(res) { });
return;
Which gave me NULLs
{"type":"Req Type : POST","array":null,"arrayVerify":"NULL"}
And I also tried as
var axios = require("axios");
var data = {};
data.array = ["One", "Two", "Three"];
axios ({
url : lv_url,
method : "POST",
params : data
})
.then(function(res) { console.log(JSON.stringify(res.data)); })
.catch(function(res) { });
return;
Which gave me everything right except it's a GET request now?
{"type":"Req Type : GET","array":["One","Two","Three"],"arrayVerify":"array"}