forked from nahidkishore/Node-todo-app
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
88 lines (78 loc) · 2.55 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require('express'),
bodyParser = require('body-parser'),
// In order to use PUT HTTP verb to edit item
methodOverride = require('method-override'),
// Mitigate XSS using sanitizer
sanitizer = require('sanitizer'),
app = express(),
port = 8000
app.use(bodyParser.urlencoded({
extended: false
}));
// https: //github.com/expressjs/method-override#custom-logic
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
// look in urlencoded POST bodies and delete it
let method = req.body._method;
delete req.body._method;
return method
}
}));
let todolist = [];
/* The to do list and the form are displayed */
app.get('/todo', function (req, res) {
res.render('todo.ejs', {
todolist,
clickHandler: "func1();"
});
})
/* Adding an item to the to do list */
.post('/todo/add/', function (req, res) {
// Escapes HTML special characters in attribute values as HTML entities
let newTodo = sanitizer.escape(req.body.newtodo);
if (req.body.newtodo != '') {
todolist.push(newTodo);
}
res.redirect('/todo');
})
/* Deletes an item from the to do list */
.get('/todo/delete/:id', function (req, res) {
if (req.params.id != '') {
todolist.splice(req.params.id, 1);
}
res.redirect('/todo');
})
// Get a single todo item and render edit page
.get('/todo/:id', function (req, res) {
let todoIdx = req.params.id;
let todo = todolist[todoIdx];
if (todo) {
res.render('edititem.ejs', {
todoIdx,
todo,
clickHandler: "func1();"
});
} else {
res.redirect('/todo');
}
})
// Edit item in the todo list
.put('/todo/edit/:id', function (req, res) {
let todoIdx = req.params.id;
// Escapes HTML special characters in attribute values as HTML entities
let editTodo = sanitizer.escape(req.body.editTodo);
if (todoIdx != '' && editTodo != '') {
todolist[todoIdx] = editTodo;
}
res.redirect('/todo');
})
/* Redirects to the to do list if the page requested is not found */
.use(function (req, res, next) {
res.redirect('/todo');
})
.listen(port, function () {
// Logging to console
console.log(`Todolist running on http://0.0.0.0:${port}`)
});
// Export app
module.exports = app;