Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (53 loc) · 1.42 KB
/
Copy pathserver.js
File metadata and controls
71 lines (53 loc) · 1.42 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
68
69
70
71
const express = require("express");
const productRoutes = require("./routes/productRoutes");
const helmet = require("helmet");
const cors = require("cors");
const rateLimit = require("express-rate-limit");
const app = express();
const PORT = 3000;
app.use(helmet());
app.use(cors({
origin: process.env.CLIENT_URL || "http://localhost:5173"
}));
const apiLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
limit: 100,
standardHeaders: "draft-7",
legacyHeaders: false,
message: {
message: "Too many requests. Please try again later."
}
});
app.use("/api", apiLimiter);
app.use(express.json());
// Log requests before the routes run
app.use((req, res, next) => {
console.log(`${req.method} ${req.url}`);
next();
});
// Connect the product router
app.use("/api/products", productRoutes);
// Normal pages
app.get("/", (req, res) => {
res.send("Welcome to my Express server!, We will make it easy to understand.");
});
// Test error route
app.get("/api/test-error", (req, res, next) => {
next(new Error("Something went wrong."));
});
// Handle unknown routes
app.use((req, res) => {
res.status(404).json({
message: "Route not found",
});
});
// Central error handler — keep this last
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({
message: "Internal server error.",
});
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}`);
});