PHP的Post数组在axios POST请求中为空

12

我正在尝试使用Vue 2.0和axios,并遇到了一些问题。当我尝试使用axios向我的post.php文件发送POST请求时,$_POST数组总是为空。

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工具时,它可以正常工作。


1
我之前发布过类似的内容,也许可以帮到你:https://dev59.com/TVgR5IYBdhLWcg3wV8Ay - A. L
1
那个 Content-Type 头部根本没有意义... - CBroe
3个回答

17

我认为你可以尝试这个,这可能是数据类型问题。

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)
});

3
在将其更改为 axios.post('api/post.php', data) 后,这个方法起作用了。 - kmoney12

10

使用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


2

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


是的!就是这样!真不敢相信所有这些麻烦都是因为一个重定向。非常感谢你提到了这一点。 - Andrei Surdu

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接