问题描述
之前我问过这个问题而无法得到答案。我能够使用方法:'得到'如下,让它工作,所以它没关系,但这次我需要使用post。在一个不同的项目中(使用react,redux,php,webpack,xampp),同样的问题已经重新出现,我正试图弄明白。所以这就是:
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)})
当我执行上述操作时,一切正常,数据记录为'doSomething'。但是,当我尝试使用axios({method:'POST'})并将php更改为$ _POST ['task']时,我收到一条错误消息,说$ _POST ['task']未定义如下:
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'];
当我尝试使用axios.post()时,我遇到了完全相同的问题。我想在这里使用帖子请求。任何人都可以为我解释这个问题吗?
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?
推荐答案
好了之后,我找到了答案。在PHP之前,必须先添加这一行才能访问任何POST数据:
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'];
根据我的理解,从axios输入的数据是JSON所以我们必须以JSON编码的字符串返回它使用file_get_contents()然后使用json_decode将其转换为来自JSON编码字符串的php变量。希望这有助于其他人。谢谢。
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.
这篇关于axios http总是返回空数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!