[英]PHP Post array empty on axios POST
我正在試用 Vue 2.0 和 axios,但遇到了一個小問題。 當我嘗試使用 axios 向我的 post.php 文件發送 post 請求時,$_POST 數組始終為空。
發布功能:
doPost: function() {
console.log("post in progress")
axios.post('api/post.php', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log(response)
console.log(response.data)
this.filter = response.data
})
.catch(e => {
this.errors.push(e)
})
}
后.php
<?php
header('Content-Type: application/x-www-form-urlencoded');
echo json_encode($_POST);
?>
請求以狀態 200 完成,但返回空對象“[]”
注意:當我將 post 端點更改為 jsonplaceholder 工具時,它工作正常。
我覺得你可以試試這個,應該是數據類型的問題。
var data = new FormData();
data.append('title', 'foo');
data.append('body', 'bar');
axios.post('api/post.php', data)
.then(response => {
console.log(response)
console.log(response.data)
this.filter = response.data
})
.catch(e => {
this.errors.push(e)
});
使用 axios 發送的數據不會放入 PHP 的$_POST
。 相反,它位於請求正文中,並且很可能是 json 格式。 要獲得它,請嘗試以下代碼:
function getRequestDataBody()
{
$body = file_get_contents('php://input');
if (empty($body)) {
return [];
}
// Parse json body and notify when error occurs
$data = json_decode($body, true);
if (json_last_error()) {
trigger_error(json_last_error_msg());
return [];
}
return $data;
}
$data = getRequestDataBody();
var_dump($data)
或者您可以像其他答案建議的那樣使用FormData
。
對我來說,問題是我在 url 中使用了 http 而不是 https。 服務器返回的 http 狀態代碼永久移動(到 https 站點)。 瀏覽器或命令行客戶端 (curl) 遵循這些重定向。 我的代碼沒有。 解決方案是在 url 中使用 https。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.