Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
66 lines (58 loc) · 2.3 KB
/
Copy pathindex.js
File metadata and controls
66 lines (58 loc) · 2.3 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
const express = require('express');
const app = express();
const path = require('path');
const { v4: uuid } = require('uuid');
app.use(express.urlencoded({ extended: true }))
// for parsing application/x-www-form-urlencoded
app.use(express.json()) // for parsing application/json
// this code shall save any data submitted through the form from a post request
app.set('views', path.join(__dirname, 'views'))
app.set('views engine', 'ejs')
const comments = [
{
// id: 1,
id: uuid(), // to make a unique id everytime
username: 'Izuru Kira',
comment: 'wabiske'
},
{
id: uuid(), // to make a unique id everytime
username: 'Byakuya Kuchiki',
comment: 'senbon zakura kageyoshi'
},
{
id: uuid(), // to make a unique id everytime
username: 'Connor',
comment: 'gamer for life'
},
{
id: uuid(), // to make a unique id everytime
username: 'Ichigo',
comment: 'substitute soulreaper...!!'
}
]
app.get('/comments/:id', (req, res) => {
// req.params.id
const { id } = req.params
// const commentId = comments.find(c => c.id === parseInt(id)); // it returns an id, only when the id is hardcoated in the database
const commentId = comments.find(c => c.id === id) // to get the random id generated by the UUID
res.render('comments/show.ejs', { commentId })
})
app.get('/comments/new', (req, res) => { // submits the form ie add the comment to the database
res.render('comments/new.ejs');
})
app.get('/comments', (req, res) => {
res.render('comments/comments.ejs', { comments }) // this line shall give access of comments to the comments.ejs
})
// (it shall be send as a post request on the form action in new.ejs)
app.post('/loading', (req, res) => {
// console.log(req.body); // using req.body is a bad practice since someone could use postman to alter the code and change its contents
const { username, comment } = req.body; // therefore save it as shown here
comments.push({ username, comment, id: uuid() }) // to add the comment with an ID on database
// to add id to the new comment use uuid https://www.npmjs.com/package/uuid
// res.send("IT WORKED");
res.redirect('/comments');
})
app.listen(3000, () => {
console.log('On port 3000 working on restful')
})