-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
73 lines (61 loc) · 1.74 KB
/
app.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
const express = require("express");
const path = require("path");
const mongoose = require("mongoose");
const bodyParser = require("body-parser");
const session = require("express-session");
const flash = require("connect-flash");
//connect the database
mongoose.set("useUnifiedTopology", true);
mongoose.connect("mongodb+srv://tharindu-nw:[email protected]/books?retryWrites=true&w=majority", { useNewUrlParser: true });
let db = mongoose.connection;
db.once("open", () => console.log("Connected to MongoDB"));
//check for db errors
db.on("error", (err) => console.log(err));
//Init app
const app = express();
const port = 3000;
let Book = require("./models/book");
//Set view engine
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "pug");
//body parser middleware
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
// parse application/json
app.use(bodyParser.json());
// set the static folder
app.use(express.static(path.join(__dirname, "public")));
//express-session middleware
app.set("trust proxy", 1); // trust first proxy
app.use(
session({
secret: "keyboard cat",
resave: true,
saveUninitialized: true,
})
);
//express messages middleware
app.use(require("connect-flash")());
app.use(function (req, res, next) {
res.locals.messages = require("express-messages")(req, res);
next();
});
//Home route
app.get("/", (req, res) => {
Book.find({}, (err, books) => {
if (err) {
console.log(err);
} else {
res.render("index", {
page_title: "Books",
books: books,
});
}
});
});
let books = require('./routes/books')
app.use('/books', books)
//Start server
app.listen(port, () =>
console.log(`Server started on http://localhost:${port}`)
);