【问题标题】:PHP Post array empty on axios POSTaxios POST上的PHP Post数组为空
【发布时间】:2017-12-01 15:31:52
【问题描述】:

我正在试用 Vue 2.0 和 axios,但遇到了一个小问题。 当我尝试使用 axios 向我的 post.php 文件发送发布请求时,$_POST 数组始终为空。

发布功能:

doPost: function() {
  console.log("post in progress")
  axios.post('api/post.php', {
      title: 'foo',
      body: 'bar',
      userId: 1
  })
  .then(response => {
    console.log(response)
    console.log(response.data)
    this.filter = response.data
  })
  .catch(e => {
    this.errors.push(e)
  })
}

post.php

<?php
header('Content-Type: application/x-www-form-urlencoded');


echo json_encode($_POST);
?>

请求已完成,状态为 200,但返回一个空对象“[]”

注意:当我将 post 端点更改为 jsonplaceholder 工具时,它工作正常。

【问题讨论】:

标签: javascript php axios


【解决方案1】:

我觉得你可以试试这个,应该是数据类型的问题。

var data = new FormData();
data.append('title', 'foo');
data.append('body', 'bar');

axios.post('api/post.php', data)
    .then(response => {
        console.log(response)
        console.log(response.data)
        this.filter = response.data
    })
    .catch(e => {
        this.errors.push(e)
});

【讨论】:

  • 这在我将其更改为:axios.post('api/post.php', data)
【解决方案2】:

用 axios 发送的数据没有放入 PHP 的$_POST。 相反,它位于请求正文中,并且很可能是 json 格式。 要获取它,请尝试以下代码:

function getRequestDataBody()
{
    $body = file_get_contents('php://input');

    if (empty($body)) {
        return [];
    }

    // Parse json body and notify when error occurs
    $data = json_decode($body, true);
    if (json_last_error()) {
        trigger_error(json_last_error_msg());
        return [];
    }

    return $data;
}


$data = getRequestDataBody();
var_dump($data)

或者您可以使用 FormData 就像其他答案所建议的那样。

【讨论】:

    【解决方案3】:

    对我来说,问题是我在 url 中使用的是 http 而不是 https。服务器返回 http 状态码 永久移动(到 https 站点)。浏览器或命令行客户端 (curl) 遵循这些重定向。我的代码没有。解决方案是在 url 中使用 https。

    【讨论】:

    • 是的!而已!无法相信所有这些麻烦都是因为重定向。非常感谢您提及这一点。
    猜你喜欢
    • 1970-01-01
    • 2020-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-12
    • 2019-08-18
    • 1970-01-01
    相关资源
    最近更新 更多