I recently needed to add Access-Control-Allow-Origin headers to resources on an API developed with CakePHP. There’s a good description of how to accomplish this from ThinkingMedia in 2015, but it uses DispatcherFilters, which have since been deprecated in favour of Middleware.
The $request and $response objects available to middleware have different interfaces than those retrieved from the event data in the dispatch filter, but the logic is essentially the same:
- Add an Access-Control-Allow-Origin header to every response.
- If the request uses the HTTP method OPTIONS—which CakePHP doesn’t deal with—then set the remaining relevant headers and return the response.
- Otherwise, pass the response on to the next level of middleware.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
<?php namespace App\Middleware; class HttpOptionsMiddleware { public function __invoke($request, $response, $next) { $response = $response->withHeader('Access-Control-Allow-Origin', '*'); if ($request->getMethod() == 'OPTIONS') { $method = $request->getHeader('Access-Control-Request-Method'); $headers = $request->getHeader('Access-Control-Request-Headers'); $allowed = empty($method) ? 'GET, POST, PUT, DELETE' : $method; $response = $response ->withHeader('Access-Control-Allow-Headers', $headers) ->withHeader('Access-Control-Allow-Methods', $allowed) ->withHeader('Access-Control-Allow-Credentials', 'true') ->withHeader('Access-Control-Max-Age', '86400'); return $response; } return $next($request, $response); } } |
James McDonald
I had a problems with OPTIONS request when using fetch from within react using Chrome.
This fix is a work of pure genius.
To install:
mkdir src/Middleware
create a new file named src/Middleware/httpOptionsMiddleware.php and put the contents of the above into it
Open src/Application.php and append the new hook for the middleware
// Add routing middleware.
->add(new RoutingMiddleware($this))
// add http options
->add( new HttpOptionsMiddleware($this))
James McDonald
Oh and I forgot at the top of src/Application.php
Near the top under the previous use statements you need to add
use App\Middleware\httpOptionsMiddleware;
Gustavo Cardoso
Thanks, a lot. I was almost giveup.
Jose
Thanks for your idea! it helped me to implement jwt seamlessly