axios http always returns with empty data

2020-06-27 14:20发布

问题:

I asked this question before and wasn't able to get an answer. I was able to do use method: 'get' like below to get it working so it was okay but this time I need to use post. In a different project (using react, redux, php, webpack, xampp) the same issue has resurfaced and I am trying to figure it out. So here it is:

register.php

  echo $_GET['task'];

index.js

  const values = {task: 'doSomething', username: 'username'}
  axios({
      url: "./server/register.php",
      timeout: 20000,
      method: 'get',
      params: values
  }).then(function(response){console.log(response.data)})

When I do the above everything is okay and the data is logged out as 'doSomething'. However, when I try using axios({method: 'POST'}) and changing the php to $_POST['task'] I get an error saying that $_POST['task'] is undefined like below:

index.js

  axios({
      url: "/projects/myProject/server/register.php",
      method: 'post',
      data: values
  }).then(function(response){console.log(response.data)})

register.php

echo $_POST['task'];

Notice: Undefined index: task

Also when I try this using axios.post() I encounter the exact same problem. I want to use a post request here. Can anyone shed some light on this for me?

回答1:

Okay after a fair amount of scratching my head I have found an answer. On the PHP this line has to be added before I can access any POST data:

$_POST = json_decode(file_get_contents('php://input'), true);
echo $_POST['task'];

From my understanding the data being inputted from axios is JSON so we must return it in a JSON encoded string using file_get_contents() and then convert this into a php variable from the JSON encoded string using json_decode. Hope this helps someone else. Thank you.



回答2:

You url has a bad format: it is a path not an url. You have to use either a relative (/register.php) or a absolute (http://localhost/register.php) url depends on how you serve this file with your web server.



回答3:

As an alternative, on the client side you may massage the data in the JavaScript before POSTing it, eliminating the need to edit the POST data on the server side:

var formatAxiosPostData = function (obj) {
// Create formData object:
    var formDataObject = new FormData();
// This step necessary when the obj contains additional overhead data,
// such as what's created on a 'this.$data' Vue.js object:
    obj = JSON.parse(JSON.stringify(obj));
// Fill formData object with the key-value pairs:
    Object.keys(obj).forEach(function (key) {
        formDataObject.append(key, obj[key]);
    });
    return formDataObject;
};

// example usage:
axios({
    url: "/projects/myProject/server/register.php",
    method: 'post',
    data: formatAxiosPostData(values)
}).then(function (response){
    console.log(response.data);
});