駆け出しのエンジニア日記

プログラミング言語勉強中の奮闘日記

RESTfulなルーティング5

今回はコメント削除のルーティングについて見ていきます。

CRUDのDの部分(delete)です。

早速記述していきます。

const express = require('express');
const app = express();
const path = require('path');
const methodOverride = require('method-override');
const { v4: uuid } = require('uuid');
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(methodOverride('_method'));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

let comments = [
{
id: uuid(),
username: 'sasaki',
comment: 'おもしろいーー!'
},
{
id: uuid(),
username: 'arita',
comment: '野球が好きです'
},
{
id: uuid(),
username: 'suzuki',
comment: '趣味は貯金'
},
{
id: uuid(),
username: 'tanaka',
comment: 'ジャンガジャンガ〜'
}
];
 
//コメント削除
app.delete('/comments/:id', (req, res) => {
const { id } = req.params;
//対象となるコメントをcomments配列から取り除く処理
//既にあるコメントidと違うidでフィルターかけて取り除く
comments = comments.filter(c => c.id !== id);
//リダイレクト・・・コメント一覧に戻る
res.redirect('/comments');
})
 
app.listen(3000, () => {
console.log('ポート3000で待ち');
});

対象となる「id」を取得して、その「id」と一致しない「id」をフィルターかけて削除していく流れになります。

そして「delete」メソッドはコメント更新の時と同様に、HTMLのフォームは「GET」か「POST」でしかリクエストを送ることができません。

show.ejsでも「method-override」というミドルウェアを使用します。

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>コメント</title>
</head>
<body>
<h1>コメント ID: <%= comment.id%></h1>
<h2><%= comment.comment %> - <%= comment.username %></h2>
<a href="/comments">一覧に戻る</a>
<a href="/comments/<%= comment.id %>/edit">編集</a>
<form method="POST" action="/comments/<%= comment.id %>?_method=DELETE">
<button>削除</button>
</form>
</body>
</html>

コメントも無事削除されています。

 

ちなみに、「method-override」はHTMLフォームの時だけ必要になるので、全部で使用することはありませんので注意してください。