RESTfulなルーティング2
今回もルーティングの続きです。
CRUDの「Create:作成」の部分です。
具体的には
・新しいコメント作成するフォームをユーザーに提供するルーティング
・新しいコメントを作成するためのルーティング
の2種類が必要になります。
では早速、「新しいコメント作成するフォームをユーザーに提供するルーティング」を記述していきます。前回のindex.jsのルーティングに追加していきます。
index.js
getメソッドを使用し、パスを「'/comments/new'」に設定しています。
const express = require('express');
const app = express();
const path = require('path');
app.use(express.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
let comments = [
配列は省略
];
app.get('/comments', (req, res) => {
res.render('comments/index', { comments });
});
//コメント新規作成フォーム
app.get('/comments/new', (req, res) => {
res.render('comments/new');
});
app.listen(3000, () => {
console.log('ポート3000で待ち');
});
new.ejs
<!DOCTYPE html>
<html lang="ja">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>新規コメント作成</title>
</head>
<body>
<h1>コメントを新規作成</h1>
<form action="/comments" method="POST">
<section>
<label for="username">ユーザー名</label>
<input id="username" type="text" placeholder="ユーザー名" name="username">
</section>
<section>
<label for="comment">コメント</label>
<br>
<textarea name="comment" id="comment" cols="30"
rows="4" placeholder="コメントを入力"></textarea>
</section>
<button>投稿</button>
</form>
<a href="/comments">一覧に戻る</a>
</body>
</html>
下記のようにコメント作成フォームの用意が完了です。
次に「新しいコメントを作成するためのルーティング」を記述するために、postメソッドを使用します。
上記のindex.jsにpostメソッドのルーティングを追加します。
//コメント作成
app.post('/comments', (req, res) => {
// ユーザーネームとコメントを「req.body」から取ってくる(今回必要なデータ)
const { username, comment } = req.body;
//配列に追加
comments.push({ username, comment });
//指定したパスにリダイレクト・・・今回はコメント一覧に戻る
res.redirect('/comments');
});
コメント入力し、投稿ボタンをクリックすると、
無事新規コメントが追加されています。