Skip to content

Commit 87bfd35

Browse files
committed
hopefully fix cors handling
1 parent c82d04f commit 87bfd35

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

backend/src/ApiRouter.php

Lines changed: 14 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,6 @@ public function __construct()
2424
protected function registerRoutes(): void
2525
{
2626
// We register [Controller, method, scope] for each route
27-
2827
$this->alto->map('GET', '/[s:site]/comments', [CommentListApiController::class, 'bypost']);
2928
$this->alto->map('GET', '/[s:site]/comments-count', [CommentListApiController::class, 'count']);
3029

@@ -46,6 +45,19 @@ protected function onPreflight(): void
4645
{
4746
// Set JSON content type for all responses
4847
header('Content-Type: application/json');
48+
49+
// Allow CORS for all origins (we check the origin header later)
50+
header('Access-Control-Allow-Origin: *');
51+
52+
// On CORS preflight requests, return the allowed methods and headers
53+
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
54+
// Handle preflight requests
55+
header('Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE');
56+
header('Access-Control-Allow-Headers: Authorization, Content-Type');
57+
header('Access-Control-Max-Age: 86400');
58+
http_response_code(200);
59+
exit;
60+
}
4961
}
5062

5163
/** @inheritdoc */
@@ -60,14 +72,7 @@ protected function onMatch(array $match): void
6072
throw new HttpException('Invalid site specified', 404);
6173
}
6274

63-
if ($app->conf('env') == 'dev') {
64-
// Allow CORS for all origins in dev mode
65-
header('Access-Control-Allow-Origin: *');
66-
} else {
67-
// Add CORS for site domain only
68-
header('Access-Control-Allow-Origin: ' . $app->conf('site_url'));
69-
header('Vary: Origin');
70-
75+
if ($app->conf('env') != 'dev') {
7176
// check origin header on mutation requests
7277
if ($_SERVER['REQUEST_METHOD'] !== 'GET' && $_SERVER['REQUEST_METHOD'] !== 'HEAD') {
7378
if (($_SERVER['HTTP_ORIGIN'] ?? '') !== $app->conf('site_url')) {

0 commit comments

Comments
 (0)