Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
81 lines (48 loc) · 2.03 KB
/
Copy pathserver.js
File metadata and controls
81 lines (48 loc) · 2.03 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
// imports
const express = require("express") //importing express package
const app = express() // creates a express application
const dotenv = require("dotenv").config() //this allows me to use my .env values in this file
const morgan = require("morgan")
const methodOverride = require("method-override")
const conntectToDB = require('./config/db')
const authRoutes = require("./routes/auth.routes")
const postsRoute = require("./routes/posts.routes")
const usersRoute = require("./routes/users.routes")
const session = require("express-session")
const passUserToView = require('./middleware/passUserToView')
const isSignedIn = require("./middleware/isSignedIn")
// Middleware
app.use(express.static('public')); //all static files are in the public folder
app.use(express.urlencoded({ extended: false })); // this will allow us to see the data being sent in the POST or PUT
app.use(methodOverride("_method")); // Changes the method based on the ?_method
app.use(morgan("dev")) // logs the requests as they are sent to our sever in the terminal
app.use(
session({
secret: process.env.SESSION_SECRET,
resave: false,
saveUninitialized: true,
})
); // uses the secret session code in the .env to encrypt the token
app.use(passUserToView) //used to set the res.locals.user for each ejs page
app.set("view engine", "ejs") //is more specific on which view engine we are using
// connect to database
conntectToDB()
app.use("/auth",authRoutes)
app.use("/posts", postsRoute)
app.use("/users", usersRoute)
app.use(isSignedIn) //all your protected routes go below this middleware
// Routes go here
app.get("/",(req,res)=>{
res.redirect("/auth/login")
})
const port = process.env.PORT || 3000
const server = app.listen(port,()=>{
console.log("Listening on port " + port)
}) // Listen on port 3000
server.on("error", (err) => { //console.log() an error if port 3000 is in use
if (err.code === "EADDRINUSE") {
console.error(` Port ${port} is already in use.`);
} else {
console.error(" Server error:", err.message);
}
});