We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

get request body with CORS

hi, i need to use CORS so i implemented it in phalcon Micro. It seems to work but i cant access to the request body. It´s always empty.

this is my delete function and i want to have file_name, verison and date at the body, but they are always empty. If i use the postmen (no cors) its work, with CORS it doesn´t.

public function deleteAction($tag) {
        $errors =[];
        $data = [];

        $data['tag'] = $tag;
        echo 'tag: '.$data['tag']."\n";
        if ((!is_null($tag)) && (!is_string($tag)))
            $errors['tag'] = 'String expected';

        if ($this->request->getPost('file_name') != null) {

            $data['file_name'] = $this->request->getPost('file_name');
            echo 'file_name: '.$data['file_name']."\n";
            if ($data['file_name'] != null) {
                if (!is_string($data['file_name']))
                    $errors['file_name'] = 'String expected';
            }

        }

       if ($this->request->getPost('version') != null) {

            $data['version'] = $this->request->getPost('version');
            echo 'Version: '.$data['version']."\n";
            if ($data['version'] != null) {
                if (!ctype_digit($data['version']) || ($data['version'] < 0))
                    $errors['version'] = 'The version must be a positive Integer';
            }
       }

        if ($this->request->getPost('date') != null) {

            $data['date'] = $this->request->getPost('date');
            echo 'date: '.$data['date']."\n";
            if ($data['date'] != null) {
                if (!ctype_digit($data['date']) || ((strlen($data['date']) < 0) || (strlen($data['date']) > 8)))
                    $errors['date'] = 'Date must be the format: YYYYMMDD';
            }

        }

    ...more code but no relevant

Does someone knows why?

do you check $this->request->getRawBody()??



5.9k

yes, thank you. this was my fault.

edited Sep '18

you can overwrite the Request class __constuct method:

<?php
public function __construct()
    {
        if (!$_POST && isset($_SERVER['REQUEST_METHOD']) && !in_array($_SERVER['REQUEST_METHOD'], ['GET', 'OPTIONS'], true)) {
            $data = file_get_contents('php://input');
            if (isset($_SERVER['CONTENT_TYPE'])
                && strpos($_SERVER['CONTENT_TYPE'], 'application/json') !== false) {
                $_POST = json_decode($data, true, 16);
            } else {
                parse_str($data, $_POST);
            }
            if (is_array($_POST)) {
                $_REQUEST = array_merge($_GET, $_POST);
            } else {
                $_POST = [];
            }
        }
    }

https://github.com/manaphp/manaphp/blob/master/ManaPHP/Http/Request.php#L19