我正忙于測試 Node.JS 的 Axios 插件,但我在處理 POST 請求時遇到了一些困難。為了測試,我有一個基本的 PHP 腳本// Identify GET Requestif(!empty($_GET)) { $type = "Req Type : GET"; $params = $_GET; $array = $_GET["array"]; $arrayVerify = gettype($array);}// Identify POST Requestif(!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 Ajaxdata = {};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(); }});我得到以下輸出{"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(); });我得到以下輸出{"type":"Req Type : POST","array":"One,Two,Three","arrayVerify":"string"}該數組似乎只是值的串聯,PHP 將其識別為字符串JQuery 似乎做了我預期的事情,但 Axios 沒有,這是為什么?我如何告訴 Axios 將數據用作 JSON?
1 回答

動漫人物
TA貢獻1815條經驗 獲得超10個贊
使用您已經嘗試過的選項:
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"));
- 1 回答
- 0 關注
- 153 瀏覽
添加回答
舉報
0/150
提交
取消