【问题标题】:process Axios POST in PHP [duplicate]在 PHP 中处理 Axios POST [重复]
【发布时间】:2017-10-03 05:46:45
【问题描述】:

我想向我的 PHP 文件发送一个 POST 请求来处理它并将数据存储在数据库中。我非常坚持,因为无论我尝试什么,$_POST 都保持为空。

有人可以帮我发送一个帖子请求并帮助我如何处理它吗?

我的 axios 请求:

// Performing a POST request
axios.post('dev/api/post.php',{ text: text, unk: unk})
  .then(function(response){
      console.log(response);
}).catch(function (error) {
      console.log(error);
});  

这是我在 PHP 中尝试过的,有些代码被注释掉了,因为不确定它是否有效..

if(isset($_POST) && !empty($_POST)){
/*  
$jsonReceiveData = json_encode($_POST);
$json_output = json_decode($jsonReceiveData);
$task = $json_ouput->text;
$uniquekey = $json_output->unk;
*/
echo $_POST;
/*
$stmt = $pdo->prepare("INSERT INTO todo (id, tekst, uniquekey) VALUES ('', :tekst, :unk)");
$stmt->bindParam(':unk', '1');
$stmt->bindParam(':tekst','testing');
$stmt->execute();
*/

}

解决方案:

$data = json_decode(file_get_contents("php://input"), true);
$task = $data['text'];

在 php://input 中找到对象

【问题讨论】:

  • 您的 axios 请求语法似乎正确,假设 { text: text, unk: unk} tetxt 和 unk 中有数据,您的 api 端点是否正确?
  • $_POST 是一个数组,echo 不起作用,尝试 print_r($_POST)
  • @David 可能我的端点不正确,但是如何处理 Axios 发布的 PHP 中的 JSON 对象?我不知道如何在 PHP 中访问它
  • 您的问题需要编辑,这是您的 PHP 代码中的问题,而不是 React 或 Axios

标签: php axios


【解决方案1】:

用户解决了它在 php://input 中“找到”对象

$data = json_decode(file_get_contents("php://input"), true);
$task = $data['text'];

正如 STEEL 所指出的,这是 PHP 代码的问题,而不是 React 或 Axios。

【讨论】:

  • 这是正确的..thnx
【解决方案2】:

只需要:

if(isset($_POST['text'])) { ... }

【讨论】:

    猜你喜欢
    • 2021-03-10
    • 2018-09-13
    • 2016-09-29
    • 2014-08-01
    • 1970-01-01
    • 2018-05-21
    • 2013-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多