-
Notifications
You must be signed in to change notification settings - Fork 258
/
Copy pathindex.js
97 lines (94 loc) · 2.94 KB
/
index.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
89
90
91
92
93
94
95
96
97
'use strict';
const http = require('node:http');
const pug = require('pug');
const auth = require('http-auth');
const basic = auth.basic(
{ realm: 'Enquetes Area.' },
(username, password, callback) => {
callback(username === 'guest' && password === 'xaXZJQmE');
}
);
const server = http
.createServer(basic.check((req, res) => {
console.info(`Requested by ${req.socket.remoteAddress}`);
if (req.url === '/logout') {
res.writeHead(401, {
'Content-Type': 'text/plain; charset=utf-8'
});
res.end('ログアウトしました');
return;
}
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
});
switch (req.method) {
case 'GET':
if (req.url === '/') {
res.write('<!DOCTYPE html><html lang="ja"><body>' +
'<h1>アンケートフォーム</h1>' +
'<a href="/enquetes">アンケート一覧</a>' +
'</body></html>');
} else if (req.url === '/enquetes') {
res.write('<!DOCTYPE html><html lang="ja"><body>' +
'<h1>アンケート一覧</h1><ul>' +
'<li><a href="/enquetes/yaki-tofu">焼き肉・湯豆腐</a></li>' +
'<li><a href="/enquetes/rice-bread">ごはん・パン</a></li>' +
'<li><a href="/enquetes/sushi-pizza">寿司・ピザ</a></li>' +
'</ul></body></html>');
} else if (req.url === '/enquetes/yaki-tofu') {
res.write(
pug.renderFile('./form.pug', {
path: req.url,
firstItem: '焼き肉',
secondItem: '湯豆腐'
})
);
} else if (req.url === '/enquetes/rice-bread') {
res.write(
pug.renderFile('./form.pug', {
path: req.url,
firstItem: 'ごはん',
secondItem: 'パン'
})
);
} else if (req.url === '/enquetes/sushi-pizza') {
res.write(
pug.renderFile('./form.pug', {
path: req.url,
firstItem: '寿司',
secondItem: 'ピザ'
})
);
}
res.end();
break;
case 'POST':
let rawData = '';
req
.on('data', chunk => {
rawData += chunk;
})
.on('end', () => {
const answer = new URLSearchParams(rawData);
const body = `${answer.get('name')}さんは${answer.get('favorite')}に投票しました`;
console.info(body);
res.write(
`<!DOCTYPE html><html lang="ja"><body><h1>${body}</h1></body></html>`
);
res.end();
});
break;
default:
break;
}
}))
.on('error', e => {
console.error('Server Error', e);
})
.on('clientError', e => {
console.error('Client Error', e);
});
const port = process.env.PORT || 8000;
server.listen(port, () => {
console.info(`Listening on ${port}`);
});