Sending correct JSON content type for CakePHP

后端 未结 1 1025
执笔经年
执笔经年 2021-01-03 10:43

In my CakePHP app I return JSON and exit for certain requests. An example of this would be trying to access the API for a login as a GET request:

header(\'Co         


        
相关标签:
1条回答
  • 2021-01-03 11:11

    You can leverage the new 2.x response object:

    public function youraction() {
        // no view to render
        $this->autoRender = false;
        $this->response->type('json');
    
        $json = json_encode(array('message'=>'GET request not allowed!'));
        $this->response->body($json);
    }
    

    See http://book.cakephp.org/2.0/en/controllers/request-response.html#cakeresponse

    Also you could use the powerful rest features and RequestHandlerComponent to achieve this automatically as documented: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

    You just need to allow the extension json and call your action as /controller/action.json. Then cake will automatically use the JsonView and you can just pass your array in. It will be made to JSON and a valid response by the view class.

    Both ways are cleaner than your "exit" solution - try to unit-test code that contains die()/exit(). This will end miserably. So better never use it in your code in the first place.

    0 讨论(0)
提交回复
热议问题