10

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()
{
    header("Access-Control-Allow-Origin: *");
}

Is this in the wrong place? As requests are still being blocked.

Update: It seems this does in fact work BUT because I am doing something like:

header('Content-Type: application/json');
echo json_encode(array('message'=>'Hello world!'));

In some of my methods it's acting as though it's overriding the header set the AppController so it's not appearing in the response for the JSON calls. Any ideas?

Update 2: Returning JSON like below, fixes the problem:

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

So apparently using header() in Cake breaks previous headers?

4

2 回答 2

14

您可以使用 cake 响应对象来执行此操作;

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

有关响应对象的更多信息; http://book.cakephp.org/2.0/en/controllers/request-response.html#setting-headers

但是, beforeRender() 回调似乎是一个更合乎逻辑的位置。

另一种选择是在您的 apache vhost 中添加此标头,或者 htaccess 示例可以在 Html5Boilerplate 的 htaccess 文件中找到,这是一件非常有趣的事情(有据可查),因为它包含许多与 cakephp 一起工作的优化出色地;

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

http://html5boilerplate.com/

于 2013-02-18T21:34:06.113 回答
-2

根据我在这里发现的内容:为 CakePHP 发送正确的 JSON 内容类型

CakePHP 中返回 JSON 的正确方法是这样的:

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

这是因为标头可以被覆盖,因此 CORS 不起作用,除非您使用 Cake 中的响应对象以“正确”的方式进行操作。

于 2013-02-18T23:45:00.817 回答