-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtodo.js
51 lines (42 loc) · 1.49 KB
/
todo.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
var express = require('express');
var session = require('cookie-session'); // Loads the piece of middleware for sessions
var bodyParser = require('body-parser'); // Loads the piece of middleware for managing the settings
var urlencodedParser = bodyParser.urlencoded({ extended: false });
var app = express();
/* Using sessions */
app.use(session({secret: 'todotopsecret'}))
/* If there is no to do list in the session,
we create an empty one in the form of an array before continuing */
.use(function(req, res, next){
if (typeof(req.session.todolist) == 'undefined') {
req.session.todolist = [];
}
next();
})
/* Route management below
.... */
.get('/todo', function(req, res) {
res.render('todo.ejs', {todolist: req.session.todolist});
})
.post('/todo/add/', urlencodedParser, function(req, res) {
if (req.body.newtodo != '') {
req.session.todolist.push(req.body.newtodo);
}
res.redirect('/todo');
})
.get('/todo/edit/:id', urlencodedParser, function(req, res) {
res.render('edit-todo.ejs', {todolistId: req.session.todolist[req.params.id]});
//res.redirect('/todo');
})
/* Deletes an item from the to do list */
.get('/todo/delete/:id', function(req, res) {
if (req.params.id != '') {
req.session.todolist.splice(req.params.id, 1);
}
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(8080);