CakePHP 3 REST API + CORS Request and OPTIONS method

随声附和 提交于 2019-12-03 14:16:06

For CakePHP 3.3+ version use this plugin : https://github.com/ozee31/cakephp-cors

João Paulo

With CakePHP 3.2+, I did in this way:

public function beforeRender(event $event) {
    $this->setCorsHeaders();
}

public function beforeFilter(event $event) {
    if ($this->request->is('options')) {
        $this->setCorsHeaders();
        return $this->response;
    }
}

private function setCorsHeaders() {
    $this->response = $this->response->cors($this->request)
        ->allowOrigin(['*'])
        ->allowMethods(['*'])
        ->allowHeaders(['x-xsrf-token', 'Origin', 'Content-Type', 'X-Auth-Token'])
        ->allowCredentials(['true'])
        ->exposeHeaders(['Link'])
        ->maxAge(300)
        ->build();
}

In this way, I can even handle CakePHP error pages.

Depending on your case, you can change values on allowHeaders array.

Remembering that if the request has withCredentials set to true, you will need to specify the origins.

in your appController place the following:

use Cake\Event\Event; //if you dont have this allready

public function beforeFilter(event $event) { //if you dont have this beforeFilter already
    if ($this->request->is('options')) {
        return $this->response;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!