Skip to content

Commit 5dca853

Browse files
author
Dennis Philipps
committed
reorder code
1 parent 4ec8396 commit 5dca853

1 file changed

Lines changed: 22 additions & 21 deletions

File tree

backend/api/db.php

Lines changed: 22 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,28 @@
33

44
require_once dirname(__DIR__) . '/config.php';
55

6+
// Function to handle CORS so the React app can communicate with this API
7+
function set_cors_headers()
8+
{
9+
// Allow any localhost origin (like frontend on 5173)
10+
if (isset($_SERVER['HTTP_ORIGIN']) && strpos($_SERVER['HTTP_ORIGIN'], 'localhost') !== false) {
11+
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
12+
} else {
13+
header("Access-Control-Allow-Origin: *");
14+
}
15+
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
16+
header("Access-Control-Allow-Headers: Content-Type, Authorization");
17+
18+
// Handle preflight requests
19+
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
20+
exit(0);
21+
}
22+
}
23+
24+
// Set JSON header and CORS for all API endpoints including this file
25+
header('Content-Type: application/json');
26+
set_cors_headers();
27+
628
$host = get_config('DB_HOST', 'localhost');
729
$db = get_config('DB_NAME', 'nester_db');
830
$user = get_config('DB_USER', 'root');
@@ -26,25 +48,4 @@
2648
exit;
2749
}
2850

29-
// Function to handle CORS so the React app (port 5173) can communicate with this API
30-
function set_cors_headers()
31-
{
32-
// Allow any localhost origin (like frontend on 5173)
33-
if (isset($_SERVER['HTTP_ORIGIN']) && strpos($_SERVER['HTTP_ORIGIN'], 'localhost') !== false) {
34-
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
35-
} else {
36-
header("Access-Control-Allow-Origin: *");
37-
}
38-
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
39-
header("Access-Control-Allow-Headers: Content-Type, Authorization");
40-
41-
// Handle preflight requests
42-
if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
43-
exit(0);
44-
}
45-
}
46-
47-
// Set JSON header and CORS for all API endpoints including this file
48-
header('Content-Type: application/json');
49-
set_cors_headers();
5051
?>

0 commit comments

Comments
 (0)