I have a problem here.
I am using Codeigniter 3.
So I created an api-builder application, well there is 1 external website that wants to use the api that has been created in the api-builder, let’s call it portal.
I created 1 javascript called global-ajax.js to call the api in the portal project like this
// ajax-global.js
const url = 'https://webserver.or.id/api/1.0/getSiswa';
$.ajax({
url: url,
type: "GET",
beforeSend: function(request) {
request.setRequestHeader("api_access_key", "xxxxxx"); // Ganti dengan API key Anda
request.setRequestHeader("web_origin", "https://portal.or.id/");
},
success: function(response) {
// Tampilkan data siswa di console
console.log('Data Siswa:', response);
},
error: function(jqXHR, textStatus, errorThrown) {
$('#output').val('Error: ' + textStatus + 'n' + errorThrown);
}
});
But when I look through the console, this error appears,
Access to XMLHttpRequest at ‘https://webserver.or.id/api/1.0/getSiswa’ from origin ‘https://portal.or.id’ has been blocked by CORS policy: Request header field web_origin is not allowed by Access-Control-Allow-Headers in preflight response.
So, how to get rid of the error and make the portal able to access the api created in api-builder (webserver)?
Because, in the api-builder controller, the requirement to be able to access the API is by providing api_access_key and web_origin for authentication.
Here is one function in the API controller (api-builder project)
private function isAuthorized()
{
$headers = getallheaders();
error_log(print_r($headers, true)); // Log header yang diterima
$api_key = $headers['api_access_key'] ?? '';
$website_origin = $headers['web_origin'] ?? '';
error_log("API Key: $api_key, Website Origin: $website_origin"); // Log nilai API Key dan Website Origin
if (empty($api_key) || empty($website_origin)) {
return false;
}
$is_key_valid = $this->M_api->validate_api_key($api_key, $website_origin);
error_log("Is Key Valid: " . ($is_key_valid ? 'true' : 'false')); // Log hasil validasi
return $is_key_valid;
}
Thank you very much