Skip to content

Instantly share code, notes, and snippets.

@yashuarc
Last active November 7, 2023 15:43
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yashuarc/10080747 to your computer and use it in GitHub Desktop.
Save yashuarc/10080747 to your computer and use it in GitHub Desktop.
Enabling CORS on CakePHP
public function beforeFilter() {
parent::beforeFilter();
$this->response->header('Access-Control-Allow-Origin','*');
$this->response->header('Access-Control-Allow-Methods','*');
$this->response->header('Access-Control-Allow-Headers','X-Requested-With');
$this->response->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
$this->response->header('Access-Control-Max-Age','172800');
}
@aymardkouakou
Copy link

aymardkouakou commented Nov 7, 2023

The middleware

class CorsMiddleware implements MiddlewareInterface
{
    /**
     * @inheritDoc
     */
    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // Calling $handler->handle() delegates control to the *next* middleware
        // In your application's queue.
        $response = $handler->handle($request);

        if ($response instanceof Response) {
            if ($request instanceof ServerRequest) {
                $response = $response
                    ->cors($request)
                    ->allowOrigin(['*'])
                    ->allowMethods(['*'])
                    ->allowHeaders(['*'])
                    ->allowCredentials()
                    ->build()
                    ->withStatus(200, __('You shall pass!!'));
            }
        }

        return $response;
    }
}

And in Application.php


            ->add(new CorsMiddleware()) // Add this line here

            // Add routing middleware.
            // If you have a large number of routes connected, turning on routes
            // caching in production could improve performance.
            // See https://github.com/CakeDC/cakephp-cached-routing
            ->add(new RoutingMiddleware($this))

            // Parse various types of encoded request bodies so that they are
            // available as array through $request->getData()
            // https://book.cakephp.org/4/en/controllers/middleware.html#body-parser-middleware
            ->add(new BodyParserMiddleware())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment