ヤマカサのプログラミング勉強日記

プログラミングに関する日記とどうでもよい雑記からなるブログです。

[N予備校]【2019年度】プログラミング入門 Webアプリ その14

プログラミング入門 Webアプリ

匿名掲示板を作るようです。

第3章 サーバーサイドプログラミング

19. UI、URI、モジュールの設計

投稿をした後に投稿一覧へと戻るようにリダイレクト処理を記述します。モジュールを分割することで仕様の変更が行いやすくなるなどのメリットがあります。

20. フォームによる投稿機能の実装

POST メソッドを使って投稿機能を実装します。

コード
  • index.html
'use strict'
const http = require('http');
const router = require('./lib/router');
const server = http.createServer((req, res) => {
    router.route(req, res);
}).on('error', (e) => {
    console.error('Server Error', e);
}).on('clientError', (e) => {
    console.error('Client Error', e);
});

const port = 8000;
server.listen(port, () => {
    console.info('Listening on' + port);
});
  • posts-hundler.js
'use strict';
const pug = require('pug');
function handle(req, res) {
  switch (req.method) {
    case 'GET':
            res.writeHead(200, {
                'Content-Type': 'text/html; charset=utf8'
            });
            res.end(pug.renderFile('./views/posts.pug'));
            break;
        case 'POST':
            let body = [];
            req.on('data', (chunk) => {
                body.push(chunk);
            }).on('end', () => {
                body = Buffer.concat(body).toString();
                const decoded = decodeURIComponent(body);
                const content = decoded.split('content=')[1];
                console.info('投稿されました: ' + content);
                handleRedirectPosts(req, res);
            });
            break;
        default:
            break;
  }
}

function handleRedirectPosts(req, res) {
    res.writeHead(303, {
        // 303: See Other
        'Location': '/posts'
    });
    res.end();
}
module.exports = {
    handle
}
  • router.js
'use strict';
const postHandler = require('./posts-handler');

function route(req, res) {
    switch (req.url) {
        case '/posts':
            postHandler.handle(req, res);
            break;
        default:
            break;
    }
}

module.exports = {
    route
};
  • posts.pug
doctype html
html(lang="ja")
  head
    meta(charset="UTF-8")
    title 秘密の匿名掲示板
  body
    h1 秘密の掲示板
    h2 新規投稿
    form(method="post" action="/posts")
      div
        textarea(name="content", cols="40", rows="4")
      div
        button(type="submit") 投稿

複数のファイルに分割されているので、機能が分かりやすくなっていると思います。

21. 認証された投稿の一覧表示機能

投稿された文章を配列に追加していき、ページ上で表示させました。この部分はデータベースを使うように改善するようです。

感想

段々とそれらしい感じになっている気がします。