Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
72 lines (54 loc) · 2.47 KB
/
Copy pathserver.js
File metadata and controls
72 lines (54 loc) · 2.47 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
// server.js
//console.log('May Node be with you')
const express = require('express');
const bodyParser= require('body-parser')
const app = express();
const MongoClient = require('mongodb').MongoClient
const connectionString = 'mongodb+srv://phuc:nguyenphuc315@cluster0.uq6xhom.mongodb.net/?retryWrites=true&w=majority'
// (0) CONNECT: server -> connect -> MongoDB Atlas
MongoClient.connect(connectionString, { useUnifiedTopology: true })
.then(client => {
console.log('Connected to Database')
// (1a) CREATE: client -> create -> database -> 'star-wars-quotes'
// -> create -> collection -> 'quotes'
const db = client.db('star-wars-quotes')
const quotesCollection = db.collection('quotes')
// To tell Express to EJS as the template engine
app.set('view engine', 'ejs')
// Make sure you place body-parser before your CRUD handlers!
app.use(bodyParser.urlencoded({ extended: true }))
// To make the 'public' folder accessible to the public
app.use(express.static('public'))
// To teach the server to read JSON data
app.use(bodyParser.json())
// (2) READ: client -> browser -> url
// -> server -> '/' -> collection -> 'quotes' -> find()
// -> results -> index.ejs -> client
app.get('/', (req, res) => {
db.collection('quotes').find().toArray()
.then(results => {
// results -> server -> console
console.log(results)
// results -> index.ejs -> client -> browser
// The file 'index.ejs' must be placed inside a 'views' folder BY DEFAULT
res.render('index.ejs', { quotes: results })
})
.catch(/* ... */)
})
// (1b) CREATE: client -> index.ejs -> data -> SUBMIT
// -> post -> '/quotes' -> collection -> insert -> result
app.post('/quotes', (req, res) => {
quotesCollection.insertOne(req.body)
.then(result => {
// results -> server -> console
console.log(result)
// -> redirect -> '/'
res.redirect('/')
})
.catch(error => console.error(error))
})
// server -> listen -> port -> 3000
app.listen(3000, function() {
console.log('listening on 3000')
})
})