Created
June 12, 2021 00:35
-
-
Save aramis-it/c9d64bfbd59dc5516e086f35cab73a7d to your computer and use it in GitHub Desktop.
cakephp 4, cors, middleware
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
declare(strict_types=1); | |
namespace App\Middleware; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use Psr\Http\Server\MiddlewareInterface; | |
use Psr\Http\Server\RequestHandlerInterface; | |
/** | |
* Cors middleware | |
*/ | |
class CorsMiddleware implements MiddlewareInterface | |
{ | |
/** | |
* Process method. | |
* | |
* @param \Psr\Http\Message\ServerRequestInterface $request The request. | |
* @param \Psr\Http\Server\RequestHandlerInterface $handler The request handler. | |
* @return \Psr\Http\Message\ResponseInterface A response. | |
*/ | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
{ | |
$response = $handler->handle($request); | |
if ($request->getHeader('Origin')) { | |
$response = $response | |
->withHeader('Access-Control-Allow-Origin', '*') | |
->withHeader('Access-Control-Allow-Headers', '*'); | |
if (strtoupper($request->getMethod()) === 'OPTIONS') { | |
$response = $response | |
->withStatus(200, __('Say cheese!')); | |
} | |
} | |
return $response; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment