简体   繁体   中英

CakePHP - sending POST requests in cakephp API and data handling

I have created a CakePHP app and after already set the routes.php files,i can send JSON requests,in order to use my app as an API. For testing,i have created a function which goes like this:

public function api() {
    if($this->request->is('post')) {
        $data1 = (string)$this->request->data['Model']['data1'];
        $data2 = (string)$this->request->data['Model']['data2'];

        //logic goes here,it does stuff and $result is the variable where the result of the login is saved
        //$data1 and $data2 are used in the logic

        $result = 'result';
        $this->set('results',$result);
        $this->set('_serialize',array('results'));
    }

}

I have also created the exact same function with another name,which is meant to be used via a web form and that works correctly. BUT,this code,at this function here,when i POST data (i use Dev HTTP Client chrome extension),it returns the $results variable empty,like it does not receive what i send :/ I send the data as follows via the chrome extension i use:

data1='stuff1'&data2='stuff2'

and it returns me just

{
"results":""
}

(while the same code works perfectly when used without json).

Did i miss something?Does it seem to do something wrong? Please help me a bit around here..

ps:if you need more info,just tell me and i'll post it.

Thank you in advance!

The correct way to access that post would be

$this->request->data['data1'];

to verify what data is being sent do this:

public function api() {
    //if($this->request->is('post')) {
        $data1 = (string)$this->request->data['Model']['data1'];
        $data2 = (string)$this->request->data['Model']['data2'];

        //logic goes here,it does stuff and $result is the variable where the result of the login is saved
        //$data1 and $data2 are used in the logic

        $result = 'result';
        //$this->set('results',$result);
        $this->set('results',array('root'=>$this->request);
        $this->set('_serialize',array('results'));
    //}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM