-
Notifications
You must be signed in to change notification settings - Fork 269
/
Copy pathindex.js
62 lines (61 loc) · 1.72 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
'use strict';
const http = require('node:http');
const pug = require('pug');
const server = http
.createServer((req, res) => {
const now = new Date();
console.info(`[${now}] Requested by ${req.socket.remoteAddress}`);
res.writeHead(200, {
'Content-Type': 'text/html; charset=utf-8'
});
switch (req.method) {
case 'GET':
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: 'パン'
})
);
}
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(`[${now}] ${body}`);
res.write(
`<!DOCTYPE html><html lang="ja"><body><h1>${body}</h1></body></html>`
);
res.end();
});
break;
default:
break;
}
})
.on('error', e => {
console.error(`[${new Date()}] Server Error`, e);
})
.on('clientError', e => {
console.error(`[${new Date()}] Client Error`, e);
});
const port = 8000;
server.listen(port, () => {
console.info(`[${new Date()}] Listening on ${port}`);
});