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.
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
return $next($request, $response);