🐺

ExpressでCRUD処理を実装

2025/02/24に公開

実装経緯

web開発をするにあたり、restfulな設計のもと、基本的なCRUD処理を実装は必須の知識だと考えた。なので、それに沿ってudemyでハンズオン形式で基本を交えつつ実装を行った。

実装環境

  • MBP:macOS Sequioia 15.3.1

言語等

  • Javascript(Node.js)
    • ejs:^3.1.10
    • express:^4.21.2
    • method-override:^3.0.0
    • uuid:^11.1.0

基本設定部分

const express = require('express');
const app = express();
--一部省略---

アプリケーションの設定

app.use(express.urlencoded({extended: true}));
---一部省略---

データの準備

let comments = [
    {
        id: uuid(),
        userName: 'yamada',
        comment: 'オモロ'
    },
    // ... 他のdata ...
];

主要CRUD部分(※)

app.get('/comments', (req, res)=>{
    res.render('comments/index', {comments});
});

app.get('/comments/new', (req,res)=>{
    res.render('comments/create');
});
app.post('/comments', (req,res)=>{
    const {userName, comment} = req.body;
    //新規投稿を追加
    comments.push({userName, comment, id: uuid()});
    res.redirect('/comments');
});
//詳細ページ表示
app.get('/comments/:id', (req,res)=>{
    const {id} = req.params;
    const comment = comments.find(c => c.id === id);
    res.render('comments/detail', {comment});
});
//編集ページ表示
app.get('/comments/:id/edit', (req, res)=>{
    const {id} = req.params;
    const comment = comments.find(c => c.id === id);
    res.render('comments/edit', {comment})
});
//更新後の遷移を含めた処理 
app.patch('/comments/:id', (req,res)=>{
    const {id} = req.params;
    const newCommentText = req.body.comment;
    const fuondComment = comments.find(c => c.id === id);
    fuondComment.comment = newCommentText;
    res.redirect('/comments');
});
app.delete('/comments/:id', (req,res)=>{
    const {id} = req.params;
    comments = comments.filter(c => c.id !== id);
    res.redirect('/comments');
})
app.listen(3000, ()=>{
    console.log('3000ポートで待機中');
});

※patchとdelete部分はformのactionを用いて実装。formはmethodとして、getやpostしか扱えないので、別の処理を追加する必要あり。

その他、詳しい実装は以下の動画購入で実装をお願いします。
【世界で90万人が受講】Web Developer Bootcamp(日本語版)

Discussion