-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
67 lines (47 loc) · 1.74 KB
/
index.js
File metadata and controls
67 lines (47 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
// => Import dependencies
import express from "express";
import path from "path";
import { fileURLToPath } from "url"; // needed for __dirname in ES modules
// => Setup path helpers
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
// => Create Express app
const app = express();
const PORT = process.env.PORT || 8080;
// => Middleware
// Serve static files (HTML, CSS, JS, images, etc.) from the "public" directory
app.use(express.static(path.join(__dirname, "public")));
// Parse incoming JSON requests (useful for APIs)
app.use(express.json());
// Middleware for logging requests
app.use((req, res, next) => {
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
next(); // Continue to the next middleware or route handler
});
// => Routes
// Serve main HTML page
app.get("/", (req, res) => {
res.sendFile(path.join(__dirname, "public", "pages", "index.html"));
});
// Serve JSON data
app.get("/api/destinations", (req, res) => {
res.sendFile(path.join(__dirname, "data", "destinations.json"));
});
// => Error Handling
// 404 Handler — runs when no route matches
app.use((req, res) => {
res.status(404).send("<h3>❌ 404 Not Found — The page you're looking for doesn't exist.</h3>");
});
// General Error Handler — catches unexpected errors
app.use((err, req, res, next) => {
console.error("🔥 Unexpected error:", err.stack);
res.status(500).send("<h3>⚠️ 500 Internal Server Error — Something went wrong.</h3>");
});
// => Start the server
app.listen(PORT, (err) => {
if (err) {
console.error("❌ Failed to start the server:", err);
process.exit(1);
}
console.log(`✅ Server running at: http://localhost:${PORT}`);
});