Sending the correct JSON content type for CakePHP

In my CakePHP application, I return JSON and exit for specific requests. An example of this would be an attempt to access the login API as a GET request:

header('Content-Type: application/json'); echo json_encode(array('message'=>'GET request not allowed!')); exit; 

However, I need an echo prefix with the content type so that it is sent as JSON. Otherwise, my code at the other end interprets it to the other.

Any ideas on how to get around this? Or at least improve it.

Update: Cake version 2.3.0

+1
source share
1 answer

You can use the new response object 2.x:

 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

You can also use the powerful rest functions and RequestHandlerComponent to achieve this automatically, as described: http://book.cakephp.org/2.0/en/views/json-and-xml-views.html

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

Both methods are cleaner than your exit solution - try running a single test code containing die () / exit (). It will end badly. Therefore, it is best to never use it in your code in the first place.

+30
source

All Articles