-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (76 loc) · 2.15 KB
/
index.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const ejsLayouts = require("express-ejs-layouts");
const morgan = require("morgan");
const methodOverride = require("method-override");
const flash = require("express-flash");
const passport = require("passport");
const session = require("express-session");
const MongoStore = require("connect-mongo")(session);
const connectDB = require("./config/db");
const mainRoutes = require("./routes/auth");
const reportRoutes = require("./routes/reports");
require("dotenv").config({ path: "./config/.env" });
require("./config/passport")(passport);
connectDB();
// Middleware & static files
app.use(express.static("public"));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
// Set Ejs templating engine
app.set("view engine", "ejs");
app.use(ejsLayouts);
// Logging
if (process.env.NODE_ENV === "development") {
app.use(morgan("dev"));
}
//Use forms for put / delete
app.use(methodOverride("_method"));
// Session
app.use(
session({
secret: "keyboard cat",
resave: false,
saveUninitialized: false,
store: new MongoStore({ mongooseConnection: mongoose.connection }),
})
);
// Passport middleware
app.use(passport.initialize());
app.use(passport.session());
//Use flash messages for errors, info, ect...
app.use(flash());
app.use("/", mainRoutes);
app.use("/reports", reportRoutes);
const PORT = process.env.PORT || 3000;
app.listen(
PORT,
console.log(`server running in ${process.env.NODE_ENV} node on port ${PORT}`)
);
// 404 page
app.use((err, req, res, next) => {
const errorStatus = err.status || 500;
const errorMessage = err.message || "Something went wrong!";
if(errorStatus === 404) {
res.status(errorStatus).render("error/404", {
title: "404",
username: req.user,
error: {
success: false,
status: errorStatus,
message: errorMessage,
stack: err.stack,
},
});
} else {
res.status(errorStatus).json({
success: false,
status: errorStatus,
message: errorMessage,
stack: err.stack,
})
}
});
// Export the Express API
module.exports = app;