Implementing cross-origin resource sharing (CORS) using middleware in CakePHP 3.3

57 sec read

I worked on a project recently where I had to allow XMLHttpRequests from a different domain. I initially thought about adding the necessary Access-Control headers at the controller level, but after doing some reading, it turned out it was a better idea to make use of a dispatcher filter. However, dispatcher filters would only apply prior to CakePHP 3.3 since they are now deprecated.

Enter middleware, which I found to be quite familiar since I have made use of a similar concept in Express during my Node.js development. Think of middleware as reusable components which you can use to handle your web requests and modify responses.

The CakePHP middleware classes should be placed in the src/Middleware folder. You can create the folder if it doesn’t already exist in your project.

We’ll create a class in the Middleware folder called CorsMiddleware.php.

The code listing is pretty straightforward. The response is modified with the necessary headers to enable the cross origin requests to be successfully handled by the browser.

You can modify the header values as you see fit, like limiting the Access-Control-Allow-Origin header to specific domains – the wildcard (*) allows requests to be accepted from all domains – or the the request methods to just GET and POST, or the allowed request headers.

To make use of the cors middleware, modify src\Application.php and add the middleware using:
$middleware->add(new CorsMiddleware())

And that’s all there is to it. There are more details about what you can do with middleware in the CakePHP documentation, so be sure to check it out.

Handle gamepad input by reading from /dev/input using C#…

Now that we have a gamepad connected over bluetooth, and we are able to detect it programmatically, the obvious next step would be to...
Akinwale
6 min read

How to programmatically detect if a gamepad is connected…

Since I managed to get the Xbox Wireless Controller connected to the PINE64 using bluetooth, I had to come up with a way to...
Akinwale
6 min read

Xbox Wireless Controller connected to the PINE64 running Ubuntu…

Although the goal of the autonomous robot project is to have a robot that can navigate without human input, it’s not a bad idea...
Akinwale
15 min read

One Reply to “Implementing cross-origin resource sharing (CORS) using middleware in CakePHP…”

Leave a Reply

Your email address will not be published. Required fields are marked *