Skip to content

Instantly share code, notes, and snippets.

@fabiocarneiro
Last active October 5, 2015 15:44
Show Gist options
  • Save fabiocarneiro/81ea4e1eb0a52b8ded12 to your computer and use it in GitHub Desktop.
Save fabiocarneiro/81ea4e1eb0a52b8ded12 to your computer and use it in GitHub Desktop.
<?php
class AddHeadersForEveryResponseMiddleware
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
return $response
->withAddedHeader('Access-Control-Allow-Origin', '*')
->withAddedHeader('Access-Control-Allow-Methods', '*')
->withAddedHeader('Access-Control-Allow-Headers', '*');
}
}
<?php
class CORSHeadersInResponseMiddleware
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
return $next($request, new JsonResponse());
}
}
<?php
return [
'routes' => [
// no route for the current path
],
'middleware_pipeline' => [
'pre_routing' => [
[
// deal with OPTIONS request only
'middleware' => AddHeadersOnlyForOptionsResponseMiddleware::class,
],
[
'middleware' => AuthenticationMiddleware::class,
'path' => '/authentication',
],
],
'post_routing' => [
[
// add headers for CORS in other requests
'middleware' => AddHeadersForEveryResponseMiddleware::class,
],
],
],
];
<?php
class AddHeadersOnlyForOptionsResponseMiddleware
{
public function __invoke(ServerRequestInterface $request, ResponseInterface $response, callable $next = null)
{
if ('OPTIONS' !== $request->getMethod()) {
return $next($request, $response);
}
return $response
->withAddedHeader('Access-Control-Allow-Origin', '*')
->withAddedHeader('Access-Control-Allow-Methods', '*')
->withAddedHeader('Access-Control-Allow-Headers', '*');
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment