react.js 使用 axios 将数据发布到 php,但 php echo 为空
我正在使用 react.js、axios 和 PHP 将数据发布到 MySQL 数据库
I am using react.js, axios, and PHP to post data to MySQL database
这是我的 react.js 代码
This is my react.js code
sendData(){
var data = new FormData();
data.append('name', 'jessie');
data.append('time', '12:00');
data.append('food', 'milk');
data.append('nutrition', 'vitaminA');
axios.post(
'./sendData.php',{
data: data
})
.then(response => {
console.log(response)
console.log(response.data)
this.filter = response.data
})
.catch(e => {
this.errors.push(e)
})
}
这是我的 PHP 代码
And this is my PHP code
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "";
$database = "mydb";
$conn = new mysqli($servername, $username, $password, $database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully yayaya";
echo "the post after this";
echo json_encode($_POST);
?>
这是我的 Chrome 控制台
And this is my Chrome Console
Connected successfully yayayathe post after this[]
我不知道为什么我的 PHP 得到空数据并回显空值.
I don't know why my PHP get empty data and echo empty value.
推荐答案
根据 axios 文档
默认情况下,axios 将 JavaScript 对象序列化为 JSON.
By default, axios serializes JavaScript objects to JSON.
一种选择是从 PHP 代码的正文中读取 json:
$entityBody = file_get_contents('php://input');
那么就不用在FormData
中包裹你的数据了,直接添加即可:
Then there's no need to wrap your data in FormData
, you can just add it directly:
axios.post(
'./sendData.php',{
data: {
name: 'jessie',
time: '12:00',
food: 'milk',
nutrition: 'vitaminA'
}
})
<小时>
另一个选项是在 axios 中设置 Content-type
头:
axios.post(
'./sendData.php',{
data: data
{
headers: {
'Content-type': 'multipart/form-data'
}
}
})
<小时>
虽然我觉得选项 1 更好
Option 1 seems better to me though
相关文章