✋Hello engineers, welcome to Webzone Tech Tips, I am Zidane, (my nickname: ιΈ‘θ)
Good
day to you. This series will share with you how to Fix Cross-Origin Resource Sharing CORS issue in Cakephp
What is CORS?
Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a "preflight" request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request. In that preflight, the browser sends headers that indicate the HTTP method and headers that will be used in the actual request.
π Tiktok
π Facebook:On Cakephp Source code when you define an Api, sometime you will get the CORS issue call from client side. But you have looking many page about this topic but still cannot fix it. So on this topic will help you how to fix CORS on server side.
These are structure of Cakephp source code.
Access on below file:
src/controller/Api/component/ApiComponent.php
looking on the init() function add below code on before call API function
Don't forget the OPTIONS. That a key issue checking for CORS issue
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);
}
---
public function init()
{
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);
}
$this->result = array(
'status' => $this->status,
'message' => __("please_provide_information"),
'params' => $this->params,
);
}