-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
82 lines (56 loc) · 2.48 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
72
73
74
75
76
77
78
79
80
81
82
// ===[ IMPORTING DEPENDENCIES ]===================================================================
var express = require('express')
var app = express()
var ejs = require('ejs')
var morgan = require('morgan')
var bodyParser = require('body-parser')
var mongoose = require('mongoose')
var Book = require('./views/dbSchemas/01-book')
require('dotenv/config') // <--- Enviroment Variables.
console.log("-----------------------------------------------------------------------")
// ===[ MIDDLE-WARE ]==============================================================================
mongoose.connect( `mongodb://${process.env.MONGO_DB_USERNAME}:${process.env.MONGO_DB_PASSWORD}@ds013564.mlab.com:13564/books1` , { useMongoClient: true } , (err) => {
console.log( (err) ? ("MLabs Conection to DataBase: FAIL..... \n --> " + err ) : "Conection to DataBase: SUCCESS... \n." )
});
var data1 = bodyParser.urlencoded({ extended: false }) // <--- BodyParser will get the information from from organize as object and save in variable data1
app.set('view engine', 'ejs')
app.use(morgan('dev'))
app.use(express.static(__dirname + '/node_modules/bootstrap/dist'))
app.use(express.static(__dirname + '/views'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))
// ===[ ROUTES ]==================================================================================
app.get('/', (req, res) => {
res.render('pages/01-index.ejs')
})
app.get('/ad', (req, res) => {
res.render('pages/02-add.ejs')
})
app.get('/al', (req, res) => {
Book.find({})
.exec(function(err, libros){
if(err){ throw err }
console.log(libros)
res.render('pages/03-all.ejs', {data: libros})
})
})
app.post('/', data1, (req, res, next) => { // <-- Posting new book to DataBase.
res.render('pages/09-done.ejs', {data: req.body})
var papiro = new Book()
papiro.title = req.body.title
papiro.author = req.body.author
papiro.category = req.body.category
papiro.save( (err, data) => {
if(err){
return console.log("Error inserting to Database: ", err)
}else {
if(err){ res.send(data) }
console.log(". \n The following Data Has Been Posted to Doatabase \n.", data)
}
})
})
// ===[ SERVER-LISTENER ]============================================================================
app.listen(5000, (err) => {
if(err){ throw err }
console.log("Server up and running.......")
})