Enabling CORS in CakePHP app

前端 未结 2 2014
青春惊慌失措
青春惊慌失措 2021-02-08 14:42

I am trying to enable CORS for an API built in CakePHP so that all requests are accessible with the following in the AppController:

public function beforeFilter(         


        
相关标签:
2条回答
  • 2021-02-08 15:09

    You can do this using the cake response object;

    $this->response->header('Access-Control-Allow-Origin', '*');
    

    More info on the response object; http://book.cakephp.org/2.0/en/controllers/request-response.html#setting-headers

    However, the beforeRender() callback seems a more logical location.

    Another option is to add this header in your apache vhost or htaccess examples can be found in the htaccess file of Html5Boilerplate which is a very interesting thing to look at (well documented), because it contains a lot of optimisations that work nicely with cakephp as well;

    https://github.com/h5bp/server-configs-apache/blob/master/dist/.htaccess

    http://html5boilerplate.com/

    0 讨论(0)
  • 2021-02-08 15:10

    Based on what I found out here: Sending correct JSON content type for CakePHP

    The correct way to return JSON in CakePHP is like so:

    $this->response->type('json');
    $this->response->body(json_encode(array('message'=>'Hello world!')));
    

    This is because the headers can be overridden and therefore the CORS doesn't work unless you do it the 'proper' way using the response object in Cake.

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