PHP Post array empty on axios POST

前端 未结 3 1165
迷失自我
迷失自我 2021-02-14 21:54

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

相关标签:
3条回答
  • 2021-02-14 22:37

    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.

    0 讨论(0)
  • 2021-02-14 22:38

    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.

    0 讨论(0)
  • 2021-02-14 22:52

    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)
    });
    
    0 讨论(0)
提交回复
热议问题