Cors setting not working what's wrong with my code?

I have created middleware and implement the following code but not working. Why ?

public function addHeaders(ServerRequestInterface $request, ResponseInterface $response): ResponseInterface
    {
        if ($request->getHeader('Origin')) {
            $response = $response
                ->withHeader('Access-Control-Allow-Origin', $this->_allowOrigin($request))
                ->withHeader('Access-Control-Allow-Credentials', $this->_allowCredentials())
                ->withHeader('Access-Control-Max-Age', $this->_maxAge());

            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());
            }

        }

        return $response;
    }

You need to give a bit more context here.
CORS is always related to 2 different domains: the client domain and the server domain.

What HTTP request do you perform form which domain and receive what error?

I am using HTTP Post request and client domain is react app and server domain is cakephp app.

After tireless search, I resolve above issue by adding the following header in : public function beforeFilter(\Cake\Event\Event $event) {

    header('content-type: application/json; charset=utf-8');
    header("access-control-allow-origin: *");
    //header('Access-Control-Allow-Methods: *');

}

Refer to : Enabling CORS on CakePHP · GitHub

I use this Middleware plugin from ozee31 which I tweaked to work in CakePHP 5.x

CakePHP has a built in CORSBuilder which helps you set headers on a response object.

See Request & Response Objects - 5.x

So basically all you’d need to do is create a middleware via bake, add it to the middleware queue and adjust the response object according to what you need.

See e.g. Request & Response Objects - 5.x

Cool thanks Kevin. I wasn’t aware of this.