-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
67 lines (56 loc) · 1.64 KB
/
app.js
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
// app.js
import cors from "cors";
import express from "express";
const expressMiddleWare = (req, res, next) => {
console.log("Middleware: This will be executed for every request.");
console.log(`[${new Date().toISOString()}] ${req.method} ${req.url}`);
req.customProperty = "Custom Value";
app.use(cors());
app.use(errorHandlerMiddleware);
next();
};
const errorHandlerMiddleware = (err, req, res, next) => {
console.error(err.stack);
res.status(500).send("Internal Server Error");
};
const app = express();
const port = 3000;
app.use(expressMiddleWare);
//Authentication handling in middle ware
const authenticateMiddleware = (req, res, next) => {
// Check authentication token or session
if (req.headers.authorization === "Bearer yourAuthToken") {
next();
} else {
res.status(401).json({ error: "Unauthorized" });
}
};
// Apply authentication middleware to specific routes
app.get("/protected-route", authenticateMiddleware, (req, res) => {
res.json({ message: "Access granted!" });
});
app.get("/", (req, res) => {
res.send("Hello, Express!");
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});
export const stopServer = () => {
app.close((err) => {
if (err) {
console.error("Error during server shutdown:", err);
process.exit(1);
}
console.log("Server closed gracefully.");
process.exit(0);
});
};
// Handle shutdown signals
process.on("SIGINT", () => {
console.log("\nReceived SIGINT. Closing server...");
// stopServer();
});
process.on("SIGTERM", () => {
console.log("\nReceived SIGTERM. Closing server...");
// stopServer();
});