I'm using vue3 with codeigniter4 .I am getting a CORS issue with fetch When sending a custom header even I set what should be set for CORS in server side method (Without using the framework filters ,Just pure php)
my js code is :
GetMyOrders() {
fetch(this.AppMainData.ApiUrl+'orders/get', {
method: 'GET',
headers:{
'Role': 'some role',
}
}).then(response => response.json())
.then(data => {
console.log(data);
this.MyOrders = data.result;
this.explode;
return;
})
}
And my php code in codeigniter controller (Not resource) is :
public function GetMyOrders(){
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Role ,Content-Type,Origin');
header('Access-Control-Allow-Credentials:true');
$db=\Config\Database::connect();
$data['result']=$db->query("Some SQL Query")->getResult();
return json_encode($data);
}
The fetch is successful when not fetching with header , but when i add my custom header the response is blocked by CORS policy as bellow:
"Access to fetch at 'http://localhost/MyApp/public/api/orders/get' from origin 'http://localhost:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
Any idea please (Without using External Solutions) !!!
It's solved .As the Bros mentioned in replies (A preflight request issue) Just adding this checking Request Code in (Routes.php) And The problem is solved
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']) &&
$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] == 'GET') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers:Role,Origin , Content-Type');
}
exit;
}
Thank U Guys