Skip to content

Commit

Permalink
Handle CORS automatically.
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek committed Nov 18, 2022
1 parent b94baa6 commit bccc068
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions src/ApiManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ public function run(?string $path = null, ?array $params = [], ?string $method =
{
$path ??= Url::get()->getRelativeUrl();
$method = $method === null || $method === '' ? Helpers::httpMethod() : $method;
$this->handleCorsRequest($method);
$params = array_merge($this->safeGetParams($path), $this->getBodyParams($method), $params ?? []);
$panel = new Panel($path, $params, $method);
$isDebugger = class_exists(Debugger::class);
Expand Down Expand Up @@ -469,4 +470,23 @@ private function formatParams(array $params): array

return $return;
}


private function handleCorsRequest(string $httpMethod): void
{
if (isset($_SERVER['HTTP_ORIGIN'])) {
header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Max-Age: 86400'); // cache for 1 day
}
if ($httpMethod === 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD'])) {
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
}
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'])) {
header('Access-Control-Allow-Headers: ' . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
}
die;
}
}
}

0 comments on commit bccc068

Please sign in to comment.