[英]Axios POST Request Unexpected Data Format
我正忙於測試 Node.JS 的 Axios 插件,但我在使用 POST 請求時遇到了一些困難。
為了測試,我有一個基本的 PHP 腳本
// 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();
作為初始測試,我使用 JQuery Ajax 如下
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(); }
});
我得到以下 output
{"type":"Req Type : POST","array":["One","Two","Three"],"arrayVerify":"array"}
看起來像格式良好的 JSON,該陣列仍然是一個陣列,PHP 將其識別為一個很好的陣列
然后當我嘗試使用 Node.js 中的 Axios
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(); });
我得到以下 output
{"type":"Req Type : POST","array":"One,Two,Three","arrayVerify":"string"}
該數組似乎只是值的串聯,PHP 將其識別為字符串
JQuery 似乎達到了我的預期,但 Axios 沒有,這是為什么呢? 如何告訴 Axios 將數據用作 JSON?
更新
我也嘗試如下
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;
這給了我NULL
{"type":"Req Type : POST","array":null,"arrayVerify":"NULL"}
我也嘗試過
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;
除了現在是 GET 請求之外,這給了我一切權利?
{"type":"Req Type : GET","array":["One","Two","Three"],"arrayVerify":"array"}
使用您已經嘗試過的選項:
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;
但是在 PHP 端,您不會填充$_POST
,而是使用php://input
:
$data = json_decode(file_get_contents("php://input"));
有關此答案的更多信息: https://stackoverflow.com/a/8893792/1580044
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.