-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_cookie.js
84 lines (76 loc) · 1.74 KB
/
app_cookie.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
var express = require('express');
var cookieParser = require('cookie-parser');
var app = express();
app.use(cookieParser('234A!!@2$$21badfgpoi'));
var products = {
1:{title:'The history of web 1'},
2:{title:'The next web'}
};
app.get('/products', function(req, res){
var output = '';
for(var name in products) {
output += `
<li>
<a href="/cart/${name}">${products[name].title}</a>
</li>`
}
res.send(`<h1>Products</h1><ul>${output}</ul><a href="/cart">Cart</a>`);
});
app.get('/cart/:id', function(req, res){
var id = req.params.id;
if(req.signedCookies.cart){
var cart = req.signedCookies.cart;
} else {
var cart = {};
}
if(!cart[id]){
cart[id] = 0;
}
cart[id] = parseInt(cart[id])+1;
res.cookie('cart', cart, {signed:true});
res.redirect('/cart');
});
app.get('/cart', function (req, res) {
var cart = req.signedCookies.cart;
if(!cart){
res.send('Empty');
} else {
var output = '';
for(var id in cart){
output += `
<li>${products[id].title} (${cart[id]})</li>
`
}
}
res.send(`
<h1>Cart</h1>
<ul>${output}</ul>
<a href='/products'>produts List</a>`);
});
app.get('/count', function(req, res){
if(req.signedCookies.count){
var count = parseInt(req.signedCookies.count);
} else {
var count = 0;
}
count = count+1;
res.cookie('count', count, {signed:true});
res.send('count : ' + count);
});
// ERROR HANDLER
app.use((req, res, next) => {
const error = new Error('Not found');
error.status = 404;
next(error);
});
app.use((error, req, res, nett) => {
res.status(error.status || 500);
res.json({
error: {
message: error.message
}
});
});
app.listen(3000, function(){
console.log('Connected 3000 port!!!');
});