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');
}
@simkimsia
Copy link

for me, just the first line alone works for CORS

@lindleywhite
Copy link

It seems like the third line is required for Chrome now.

@vetional
Copy link

My GET requests are getting through but for the POST requests this gives : No 'Access-Control-Allow-Origin' header is present on the requested resource.

@pgunsolley
Copy link

pgunsolley commented Nov 21, 2017

I'm having the opposite issue; my POST requests are fine, however my GET requests are giving me "No 'Access-Control-Allow-Origin' header is present on the requested resource. I think my solution is similar, but in the middleware context. Not much info about this unfortunately.

public function middleware($middlewareQueue)
{
    $middlewareQueue
        // ...
        // Add CORS for development environments.
        ->add(function($request, $response, $next) {
            return $next($request, $response)
                ->withHeader('Access-Control-Allow-Origin', 'http://localhost:3000')
                ->withHeader('Access-Control-Allow-Methods', '*')
                ->withHeader('Access-Control-Allow-Credentials', 'true')
                ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With')
                ->withHeader('Access-Control-Allow-Headers', 'Content-Type')
                ->withHeader('Access-Control-Allow-Type', 'application/json');
        });

    return $middlewareQueue;
}

@dsigner1704
Copy link

Hello everyone, I also have the same problem on my version of cakephp, I'm in version 2.8.
Unfortunately none of the codes mentioned above work for me, it's been several days since I can not solve this problem.
Thank you in advance for your help.

@farhoudi
Copy link

farhoudi commented Apr 9, 2019

Just in case:
Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

@francisnadal
Copy link

Just in case:
Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

been wondering for 2 days where to put it. Thank you very much, you're a savior!

@iman9714
Copy link

iman9714 commented Apr 8, 2020

Just in case:
Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

oh my god thank you very much, been wondering almost a week for this

@emanueledona
Copy link

Just in case:
Inside bootstrap.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    exit(0);
}

Hi all,
there is any definitive solution at the question? Add there rows to bootstrap.php isn't correct and generate problems with command line tool.

I have find a plugin for CakePHP https://github.com/ozee31/cakephp-cors but with cakephp 4.1.5 seem not working properly and POST, PUT, DELETE method can't be call cause by OPTIONS 404 error.

Seem that they take care of it in cakephp doc but marginally and not with conviction to make it risolutive: https://book.cakephp.org/4/en/controllers/request-response.html#setting-cross-origin-request-headers-cors .

Any one has try and success implement the method in doc?

@emanueledona
Copy link

Hi all,
I have finally found a more structure way in CakePHP 4.x to manage CORS.

I have created a middleware, inspired by the https://github.com/ozee31/cakephp-cors that finally manage correctly the OPTIONS preflying call.

        if (strtoupper($request->getMethod()) === 'OPTIONS') {
            $response = $response
                ->withHeader('Access-Control-Expose-Headers', $this->_exposeHeaders())
                ->withHeader('Access-Control-Allow-Headers', $this->_allowHeaders($request))
                ->withHeader('Access-Control-Allow-Methods', $this->_allowMethods())
                ->withStatus(200,__('You shall pass!!'));
        }

With the last row ->withStatus(200,'some text here'); it works correctly.

I hope this give an help to someone.

@kamleshwebtech
Copy link

I want to allow 2 domains and a subdomain. How can I do this? Allowing all the websites/subdomains are not good solution. Any suggestion. Thanks.

@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