-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
65 lines (55 loc) · 1.27 KB
/
server.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
const config = require("./config/config");
const port = config.PORT;
const helmet = require("helmet");
const rateLimit = require("express-rate-limit");
const cors = require("cors");
const express = require("express");
const connectDB = require("./src/database.js");
const path = require("path");
const { body, validationResult } = require("express-validator");
const app = express();
// security middleware
app.use(helmet());
app.set("trust proxy", "loopback");
app.use(
rateLimit({
// 100 requests per 15 minutes
windowMs: 15 * 60 * 1000,
max: 100,
})
);
// CORS middleware
app.use(
cors({
origin: "http://localhost:3000",
})
);
// JSON parsing middleware
app.use(
express.json({
extended: false,
})
);
// input validation and sanitization middleware
app.use((req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
next();
});
// routes
const postRoutes = require("./src/route/postRoutes");
app.use("/api", postRoutes);
// database connection
connectDB()
.then(() => {
app.listen(port, () => {
console.log("Server started on port " + port);
});
})
.catch((err) => {
console.error("Error connecting to MongoDB:", err.message);
process.exit(1);
});
module.exports = app;