前言
本文為「Node 入門」一文的學習筆記。
目標
建立一個表單,可以輸入文字,並呈現出來。
做法
新增 server.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
| const http = require('http'); const url = require('url');
const server = { start(route, handle) { const onRequest = (request, response) => { request.setEncoding('utf8');
const { path } = url.parse(request.url);
let data = ''; request.addListener('data', (chunk) => { data += chunk; });
request.addListener('end', () => { route(handle, path, response, data); }); };
http.createServer(onRequest).listen(8888); }, };
exports.server = server;
|
新增 router.js
檔。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| const router = { route(handle, path, response, data) { if (typeof handle[path] === 'function') { return handle[path](response, data); } response.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', }); response.write('Not Found'); response.end(); }, };
exports.router = router;
|
新增 requestHandlers.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
| const querystring = require('querystring');
const requestHandlers = { start(response, data) { const body = '<html>' + '<head>' + '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />' + '</head>' + '<body>' + '<form action="/upload" method="POST">' + '<input type="text" name="text" />' + '<input type="submit" />' + '</form>' + '</body>' + '</html>';
response.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', }); response.write(body); response.end(); }, upload(response, data) { response.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8', }); response.write(querystring.parse(data).text); response.end(); }, };
exports.requestHandlers = requestHandlers;
|
新增 index.js
檔。
1 2 3 4 5 6 7 8 9 10 11
| const { server } = require('./server'); const { router } = require('./router'); const { requestHandlers } = require('./requestHandlers');
let handle = { '/': requestHandlers.start, '/upload': requestHandlers.upload, }
server.start(router.route, handle);
|
啟動伺服器。
前往 http://localhost:8888 瀏覽。