LoginSignup
0
0

More than 1 year has passed since last update.

Expressでシンプルな掲示版を作る

Posted at

はじめに

Expressを使ってシンプルな掲示板を作る手順を説明します。

ソースコード
https://github.com/jeronimo34/SimpleBBS

初期設定

以下のコマンドを実行しアプリの雛形を作成します。
テンプレートエンジンに pug を選択します。

npm install express-generator -g
express --view=pug SimpleBBS
cd SimpleBBS
npm install

投稿一覧表示実装

投稿データの保存先

app.locals.postsに投稿データを保存します。app.localsに設定した値はアプリケーションの存続期間中、持続します。
アプリケーションを再起動すると投稿データが失われてしまうため、本来はDBにデータを保存すべきですが、今回は簡単のためapp.localsを使用します。

app.js
// データベース
app.locals.posts = [
  {
    name:"test1", text: "hogetext"
  },
  {
    name:"test2", text: "hogetext"
  },
  {
    name:"test3", text: "hogetext"
  },
];

投稿一覧の表示

http://localhost:3000 にアクセスしたときの処理を実装します。

index.js
router.get('/', function(req, res, next) {
  const posts = req.app.locals.posts;
  // 投稿一覧画面を描画。タイトルと投稿データを伝達。
  res.render('index', { title: 'SimpleBBS' , posts: posts });
});

投稿データを全て表示します。

index.pug
  div(class="posts")
    each post in posts 
      div(class="post")
        div 名前: #{post.name}
        div 本文: #{post.text}

新規投稿処理

おまじない

Formから投稿データを取得するためにbody-parserを有効にします。

app.js
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: true}));

投稿フォームを追加

投稿データを入力するFormを作成します。

index.pug
  form(method="post" action="/post/add")
    div
      label 名前: 
        input(type="textbox" name="name")
    div
      label 本文: 
        input(type="textbox" name="text")
    button(type="submit") 投稿

新規投稿処理

フォームから受け取った投稿データを、app.locals.postsに保存する処理を実装します。
routesフォルダ以下にpost.jsを作成します。

post.js
var express = require('express');
var router = express.Router();

// 新規投稿
router.post('/add', function(req, res, next) {
    // 投稿データ全取得
    let posts = req.app.locals.posts;

    // 新規投稿データ作成
    posts.unshift({name:req.body.name, text:req.body.text });
    res.redirect('/');
});

module.exports = router;

ルーターに/postを登録します。これにより、http://localhost:3000/postにアクセスしたとき、post.jsに定義した処理が実行されます。

app.js
var postRouter = require('./routes/post');
app.use('/post', postRouter);

動作確認

set DEBUG=SimpleBBS:* & npm start

image.png

おわりに

現状、改善点が多く残っています。
改善方法についても別記事で説明できればいいなと考えています。
・バリデーション処理
・データの永続化
・レイアウトの改善
etc...

参考

https://web-camp.io/magazine/archives/5652
https://nodejs.keicode.com/nodejs/express-params-form.php

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0