-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
42 lines (31 loc) · 1.42 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
import path from "path"; // path is a core module in Node.js, use it for working with file and directory paths, i.e.: to get the path to the current file
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import helmet from "helmet"; // helps secure Express apps by setting HTTP headers
import cookieParser from "cookie-parser";
// custom
import { connectDB } from "./src/config/connectDB.js";
import errorMiddleware from "./src/middleware/errorMiddleware.js";
import { appRouter } from "./src/routers/appRouter.js";
dotenv.config(); // loads environment variables from a .env file into process.env
const SERVER_PORT = process.env.SERVER_PORT || 5000;
const DB_URL = process.env.MONGO_URI;
const app = express();
app.use(express.json()); // parse body; must be before the appRouter, otherwise the request body will be undefined in the HTTP POST request
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(helmet()); // sets HTTP headers to secure the app
app.use(cookieParser());
app.use("/", appRouter); // the path / uses the appRouter function from the appRouter.js file
app.use(errorMiddleware);
const startServer = async () => {
try {
app.listen(SERVER_PORT, () => {
console.log(`Server is running on port ${SERVER_PORT}` + " 🦅");
});
} catch (error) {
throw new Error(`Error starting server: ${error}`);
}
};
connectDB(DB_URL).then(() => startServer());