axios http always returns with empty data

南楼画角 提交于 2019-12-03 21:39:49

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.

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.

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