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
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php namespace App\Middleware; class CorsMiddleware { public function __invoke($request, $response, $next) { $response = $next($request, $response); $response = $response->withHeader('Access-Control-Allow-Origin', '*')-> withHeader('Access-Control-Allow-Methods', 'DELETE, GET, OPTIONS, PATCH, POST, PUT')-> withHeader('Access-Control-Allow-Headers', 'Accept, Authorization, Cache-Control, Content-Type, X-Requested-With, x-csrf-token')-> withHeader('Access-Control-Allow-Credentials', 'true')-> withHeader('Access-Control-Max-Age', '3600'); return $response; } } ?> |
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.