Resolve CORS and CORB in CodeIgniter 4 πŸ”₯

Resolve CORS (Cross-Origin Resource Sharing) in CodeIgniter 4 πŸ”₯:

The browsers, before execute real request, execute pre-flight request (see https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request), pre-flight request use ‘OPTIONS’ method. This is general and insecure solution, you have to customize this solution for you.

In routes.php file add ‘options’ route:

$routes->options('(:any)', 'YourControllerName::options'); //one options method for all routes.

In “YourControllerName.php”, setting correct headers and correct status code:

public function options(): Response
    {
        return $this->response->setHeader('Access-Control-Allow-Origin', '*') //for allow any domain, insecure
            ->setHeader('Access-Control-Allow-Headers', '*') //for allow any headers, insecure
            ->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE') //method allowed
            ->setStatusCode(200); //status code
    }

Resolve CORB (Cross-Origin Read Blocking) in CodeIgniter 4 πŸ”₯:

CORB is response at the real request (see https://www.chromestatus.com/feature/5629709824032768), as for CORS, if you adding correct headers before any response, the problem solve, example:

public function setResponse($body = null, $statusCode = 200): Response
    {
        if (is_null($body)) {
            $body = null;
        } elseif (!is_string($body)) {
            $body = $this->format($body);
        } else {
            $body = '"' . $body . '"';
        }

        $this->response->setHeader('Access-Control-Allow-Origin', '*')
            ->setHeader('Access-Control-Allow-Headers', '*')
            ->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, DELETE');
        return $this->respond($body, $statusCode);
    }

You can automatize this procedure, example, creating a class to perform before any response. πŸ˜ƒ

Leave a Reply

Your email address will not be published. Required fields are marked *