12

I'm trying out Vue 2.0 and axios and I've got a little issue. When I try to send a post request using axios to my post.php file the $_POST array is always empty.

Post function:

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

The request is completed with status 200 but returns an empty object "[]"

Note: when I change the post endpoint to jsonplaceholder tool it works fine.

Avi
  • 141
  • 1
  • 1
  • 3
  • 1
    I posted something similar a while ago, maybe it'll help https://stackoverflow.com/questions/41457181/axios-posting-params-not-read-by-post – A. L Jun 28 '17 at 10:21
  • 1
    That Content-Type header makes absolutely no sense ... – CBroe Jun 28 '17 at 10:28

3 Answers3

17

I think you can try this, it should be the data-type problem.

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)
});
Phiter
  • 14,570
  • 14
  • 50
  • 84
gy134340
  • 566
  • 5
  • 19
10

The data that is send with axios is not put into PHP's $_POST. Instead, it is in the request body and most likely in json format. To get it, try the following code:

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)

Or you could use FormData like the other answer suggests.

arkuuu
  • 619
  • 7
  • 23
2

For me the problem was that I was using http instead of https in the url. The server returned http status code Permanently moved (to the https site). A browser or command line client (curl) follow these redirects. My code did not. Solution was to use https in the url.

mvandillen
  • 904
  • 10
  • 17
  • YES! That's it! Can't believe that all this hassle is because of an redirect. Thank you so much for mentioning this. – Andrei Surdu Jun 07 '21 at 15:53