-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
71 lines (57 loc) · 2.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
66
67
68
69
70
71
require("dotenv").config();
const express = require("express");
const app = express();
const path = require("path");
const cors = require("cors");
const cookieeParser = require("cookie-parser");
const mongoose = require("mongoose");
const connectDB = require("./config/dbConn");
const { logger } = require("./middleware/logEvents");
const errorHandler = require("./middleware/errorHandler");
const crosOptions = require("./config/coreOptions");
const verifyJWT = require("./middleware/verifyJWT");
const PORT = process.env.PORT || 2500;
// Connect to mongoDB
connectDB();
// custom middleware
app.use(logger);
// Cros Origin Source Sharing ( Its Kind of Third Party Middleware )
// whiteList can only the origin which can access
app.use(cors(crosOptions));
// Buid-in middleware to handle urlencoded data
// in other words, form data;
// content-type: application/x-www-form-uelencoded
app.use(express.urlencoded({ extended: false }));
// build-in middleware for json
app.use(express.json());
// middleware for cookiees
app.use(cookieeParser());
// server static files
app.use("/", express.static(path.join(__dirname, "/public")));
// routes
// following routes we can access without token to genrate or register random person
app.use("/", require("./routes/root"));
app.use("/register", require("./routes/api/register"));
app.use("/auth", require("./routes/api/auth"));
app.use("/refresh", require("./routes/api/refresh"));
app.use("/logout", require("./routes/api/logout"));
// This route need authentication, so thats why I added the auth middleware to generate the token using which randon user cant access without permission
app.use(verifyJWT);
app.use("/employees", require("./routes/api/employees"));
// Any route that made this far, follwing response will get respectively
app.get("*", (req, res) => {
res.status = 404;
// if(req.accepted('html')){
res.sendFile(path.join(__dirname, "views", "404.html"));
// }else if(req.accepted('json')){
// res.json({ error: '404 Not Found'})
// }else {
// res.type('txt').send('404 Not Found')
// }
});
// Middleware respond the error if crosOptions send failed message
app.use(errorHandler);
mongoose.connection.once("open", () => {
console.log("MongoDB Connected");
app.listen(PORT, () => console.log(`Server running at PORT : ${PORT} ...`));
});