Hello there. May I ask how to set up the CORS for the my CakePHP API and AngularJS frontend? I already put in the AppController@beforeFilter the following snippet but my AngularJS app says that the Origin is not setup.
public function beforeFilter(Event $event) { parent::beforeFilter($event); $this->Auth->allow(['login', 'index', 'view', 'getAllWithArticles', 'getAll', 'getLast', 'getMenuInfo']); $this->response->cors($this->request) ->allowOrigin('*') ->allowMethods(['PUT','POST', 'OPTIONS']) ->allowHeaders(['X-CSRF-Token']) ->allowCredentials() ->exposeHeaders(['Link']) ->maxAge(300) ->build(); }
This might help you https://gist.github.com/ADmad/8547377
But this one is for CakePHP 2 right? I’m using CakePHP 3 as backend.
That will work the same Kenjhim… You just need to adapt the code to Cake 3, read the documentation section on creating dispatcher filters
I already created the CorsFilter in src/Routing/Filter/CorsFilter.php with the following code
class CorsFilter extends DispatcherFilter { public function beforeDispatch(Event $event) { if ($event->data['request']->is('OPTIONS')) { $event->stopPropagation(); $event->data['response']->header(array( 'Access-Control-Allow-Origin' => '*', 'Access-Control-Allow-Methods' => 'POST, PUT, DELETE, GET, HEAD', 'Access-Control-Allow-Headers' => 'Origin, X-Requested-With, Content-Type, Authorization' )); return $event->data['response']; } } }
I also loaded in the bootstrap.php:
DispatcherFactory::add('Cors');
But I still cannot make it work. Please help.
Did you find a solution?
I tried all of the above with Cake 3.8 and nothing worked for me.
Finally, it was this plugin (installed via composer) that saved the day: ozee31/cakephp-cors
I suggest you give it a try.
Here’s my sample config for the plugin in app.php:
/**
* CORS Configuration
* Based on CORS Plugin from: https://github.com/ozee31/cakephp-cors
*/
'Cors' => [
// Accept all origins
'AllowOrigin' => '*',
// Allow Credentials
'AllowCredentials' => true,
// Allowed Methods
'AllowMethods' => [
'OPTIONS',
'GET',
'POST',
'PUT',
'PATCH',
'DELETE'
],
// Accept many Headers
'AllowHeaders' => [
'Access-Control-Allow-Headers',
'Access-Control-Allow-Origin',
'Access-Control-Request-Method',
'Access-Control-Request-Headers',
'Authorization',
'X-Requested-With',
'X-CSRF-Token',
'X-Auth-Token',
'Origin',
'Content-Type',
'Accept',
'Client-Security-Token'
],
// Expose Headers
'ExposeHeaders' => [ 'Link' ],
// Max age: 1 day
'MaxAge' => 86400,
]