forked from adityabhagat007/CollegeGeeks
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
115 lines (86 loc) · 2.38 KB
/
app.js
File metadata and controls
115 lines (86 loc) · 2.38 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
/********** CORE MODULES **********/
const path = require("path");
/********** NPM MODULES ***********/
require("dotenv").config();
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const mongoose = require("mongoose");
const session = require("express-session");
const MongoStore = require("connect-mongo");
const flash = require("connect-flash");
const PORT = process.env.PORT || 3000
/************* CUSTOM MODULES *************/
const feedRoutes = require("./routes/feed");
const authRoutes = require("./routes/auth");
/**************** INITIAL SETUP ***********************/
const app = express();
if(process.env.NODE_ENV === 'production') {
app.use((req, res, next) => {
if (req.header('x-forwarded-proto') !== 'https')
res.redirect(`https://${req.header('host')}${req.url}`)
else
next()
})
}
app.set("view engine", "ejs");
app.use(
bodyParser.urlencoded({
extended: true,
})
);
/*****************SESSION SETUP *************/
const store = MongoStore.create({
mongoUrl: process.env.DB_URL,
collectionName: "sessions",
});
app.use(
session({
secret: process.env.SECRET,
resave: false,
saveUninitialized: false,
store: store,
})
);
/************* Flash Setup ***********/
app.use(flash());
/**** CORES Settings ****/
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, PATCH, DELETE"
);
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
next();
});
/************* Static files ***********/
app.use(express.static(path.join(__dirname, "public")));
app.use(express.static(path.join(__dirname, "css")));
/********** SETTING UP ROUTES *************/
app.use(feedRoutes);
app.use(authRoutes);
/************* Error Handling ************/
app.use((error, req, res, next) => {
console.log(error);
res.render("500");
});
/************* 404 Not Found */
app.use("*", (req, res, next) => {
res.render("page404");
});
/******** SERVER SETUP **********/
mongoose
.connect(process.env.DB_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log("Connected to DB server");
app.listen(PORT, () => {
console.log(`Server started on port ${PORT}`);
});
})
.catch((err) => {
console.log(err);
});