CakePHP 3 and AngularJS integration - CORS setup

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

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:

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:
'Cors'           => [
    // Accept all origins
    'AllowOrigin'      => '*',
    // Allow Credentials
    'AllowCredentials' => true,
    // Allowed Methods
    'AllowMethods'     => [
    // Accept many Headers
    'AllowHeaders'     => [
    // Expose Headers
    'ExposeHeaders'    => [ 'Link' ],
    // Max age: 1 day
    'MaxAge'           => 86400,