Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions form.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title>アンケート</title>
</head>

<body>
<h1>どちらが食べたいですか?</h1>
<form method="post" action="/enquetes/yaki-tofu">
名前<input type="text" name="name">
<input type="radio" name="yaki-tofu" value="焼き肉"> 焼き肉
<input type="radio" name="yaki-tofu" value="湯豆腐"> 湯豆腐
<button type="submit">投稿</button>
</form>
</body>
</html>
17 changes: 13 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,41 @@
'use strict';
const http = require('node:http');
const fs = require('node:fs');
const server = http
.createServer((req, res) => {
const now = new Date();
console.info(`[${now}] Requested by ${req.socket.remoteAddress}`);
res.writeHead(200, {
'Content-Type': 'text/plain; charset=utf-8'
'Content-Type': 'text/html; charset=utf-8'
});

switch (req.method) {
case 'GET':
res.write(`GET ${req.url}\n`);
const rs = fs.createReadStream('./form.html');
rs.pipe(res);
break;
case 'POST':
res.write(`POST ${req.url}\n`);
let rawData = '';
req
.on('data', chunk => {
rawData += chunk;
})
.on('end', () => {
console.info(`[${now}] Data posted: ${rawData}`);
// const decoded = decodeURIComponent(rawData);
// console.info(`[${now}] 投稿: ${decoded}`);
const answer = new URLSearchParams(rawData);
const body = `${answer.get('name')}さんは${answer.get('yaki-tofu')}に投票しました`;
console.info(`[${now}] ${body}`);
res.write(
`<!DECOTYPE html><html lang="ja"><body><h1>${body}</h1></body></html>`
);
res.end();
});
break;
default:
break;
}
res.end();
})
.on('error', e => {
console.error(`[${new Date()}] Server Error`, e);
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
"author": "PatrickHarumi <patrickharumi@gmail.com>",
"license": "ISC",
"repository": "git@github.com:PatrickHarumi/node-js-http-3014.git"
}