Avi*_*Avi 3 javascript php axios
我正在尝试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)
})
}
Run Code Online (Sandbox Code Playgroud)
post.php中
<?php
header('Content-Type: application/x-www-form-urlencoded');
echo json_encode($_POST);
?>
Run Code Online (Sandbox Code Playgroud)
请求以状态200完成,但返回空对象"[]"
注意:当我将post端点更改为jsonplaceholder工具时,它工作正常.
我想你可以尝试这个,它应该是数据类型的问题.
var data = new FormData();
data.append('title', 'foo');
data.append('body', 'bar');
axios.post('api/post.php', {
data: data
})
.then(response => {
console.log(response)
console.log(response.data)
this.filter = response.data
})
.catch(e => {
this.errors.push(e)
});
Run Code Online (Sandbox Code Playgroud)
使用 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)
Run Code Online (Sandbox Code Playgroud)
或者您可以FormData像其他答案建议的那样使用。