react.js using axios to post data to php, but php echo empty

家住魔仙堡 提交于 2019-12-06 02:29:37

问题


I am using react.js, axios, and PHP to post data to MySQL database

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)
})
}

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);

?>

And this is my Chrome Console

Connected successfully yayayathe post after this[]

I don't know why my PHP get empty data and echo empty value.


回答1:


According to the axios docs

By default, axios serializes JavaScript objects to JSON.

One option is to read json from the body in your PHP code:

$entityBody = file_get_contents('php://input');

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'
  }
})

Another option is to set the Content-type header in axios:

axios.post(
  './sendData.php',{
  data: data
  {
    headers: {
      'Content-type': 'multipart/form-data'
    }
  }
})

Option 1 seems better to me though




回答2:


Try to take json from phpinput it is halpfull for me:

echo file_get_contents('php://input');
echo json_decode(file_get_contents('php://input'), true);



回答3:


Don't use hack, make proper code for your project.

First of all install this qs node package in your project. Then you can you stringify your data using this function and submit data to the server.

axios already clear that issue on its documentation file. You can check using-applicationx-www-form-urlencoded-format link for more info.

Whatever is use the easy way to resolve this issue in my scenario, here is my code:

var qs = require('qs');  
var palyload = {
    'command': 'userLogin',
    "email" : this.state.email,
    "password" : this.state.password,
};
axios.post( apiBaseUrl, qs.stringify(palyload) ).then(
    function(response){
        console.log(response);
    }
);

then you PHP server show proper global data like as below:

Array
(
    [command] => userLogin
    [email] => asdf@test.com
    [password] => af12548@$
)


来源:https://stackoverflow.com/questions/46274928/react-js-using-axios-to-post-data-to-php-but-php-echo-empty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!