Notice
Recent Posts
Recent Comments
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

SYDev

[Express] 12. Update Topic POST 본문

대딩코딩/웹개발 스터디

[Express] 12. Update Topic POST

시데브 2023. 12. 1. 18:42

Update Topic GET&POST

 파일명: topic.ejs

<h1><%= topic.title %></h1>
<p><%= topic.content %></p>

<form action="/topic/delete/<%= topic.topic_id %>" method="post">
    <button>Delete</button>
    <a href="/topic/update/<%= topic.topic_id %>">Update</a>
</form>

>>각 topic에 Update 버튼 추

 

 파일명: main.js

const express = require('express');
const app = express();
const port = 3000;

const bodyParser = require('body-parser'); 
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())

//app.set - 환경변수 설정
//app.use - 모든 리퀘스트에 대해서 괄호 안의 내용을 적용
//app.get - 경로에 대한 get 방식의 요청에 대한 뒤 함수 처리를 해줌

app.set('view engine', 'ejs');  
app.set('views', 'views');  


const expressLayouts = require('express-ejs-layouts');
app.use(expressLayouts);
app.set('layout', 'index.ejs');
app.set('layout extractStyles', true); 
app.use(express.static('public'));  

const homeController = require('./controllers/homeController.js');
const topicController = require('./controllers/topicController.js');

app.get('/', homeController.getTopics);
app.get('/topic/read/:topic_id', topicController.viewTopic);    
app.get('/topic/create', topicController.createTopic);  
app.post('/topic/create', topicController.createNewTopic); 
app.post('/topic/delete/:topic_id', topicController.deleteTopic);   
app.get('/topic/update/:topic_id', topicController.updateTopic);    //get 방식 update
app.post('/topic/update/:topic_id', topicController.updateNewTopic);   //post 방식 update


app.listen(port, () => {
    console.log(`Example app listening on port ${port}`);
});

 

 

 파일명: topicController.js

const topicModel = require('../models/topicModel.js');  
const homeModel = require('../models/homeModel.js');   

module.exports = {
    viewTopic: async (req, res) => {
        const topicId = req.params.topic_id;
        const topic = await topicModel.getTopic(topicId);
        const topics = await homeModel.home(); 

        res.render('topic.ejs', {topics: topics, topic: topic});
    },
    createTopic: async (req, res) => {
        const topics = await homeModel.home(); 
        res.render('createTopic.ejs', {topics: topics});
    },
    createNewTopic: async (req, res) => {
        const newTopicData = req.body;
        const insertId = await topicModel.createTopic(newTopicData);    

        res.redirect(`/topic/read/${insertId}`);    
    },
    deleteTopic: async (req, res) => {
        const topicId = req.params.topic_id;
        await topicModel.deleteTopic(topicId);

        res.redirect('/');
    },
    updateTopic: async (req, res) => {
        const topicId = req.params.topic_id;
        const topic = await topicModel.getTopic(topicId);
        const topics = await homeModel.home(); 
        res.render('updateTopic.ejs', {topics: topics, topic: topic});	//updateTopic.ejs 내용을 index.ejs body태그에 렌더링
    },
    updateNewTopic: async (req, res) => {
        const newTopicData = req.body;
        const topicId = req.params.topic_id;
        await topicModel.updateTopic(newTopicData, topicId);   

        res.redirect(`/topic/read/${topicId}`);	//수정된 해당 토픽 상세정보로 redirect
    }
}

 

 파일명: updateTopic.ejs

<link rel="stylesheet" href="/css/input.css">

<form action="/topic/update/<%= topic.topic_id %>" method="post">
    <input type="text" name="title" class="input-text" placeholder="title.." value="<%= topic.title %>">
    <textarea name="content" id="" class="input-textarea" cols="30" rows="10" placeholder="content.."><%= topic.content %></textarea>
    <button>Submit</button>
</form>

>>CreateTopic.ejs와 유사하나,  value="<%= topic.title %>", <%= topic.content %>로 박스에 원래 내용 기입

 

 파일명: topicModel.js

const db = require('../config/db.js');

module.exports = {
    getTopic: async (topicId) => {
        const query = 'SELECT * FROM Topics WHERE topic_id=?;';
        const topic = await db.query(query, [topicId]);

        return topic[0][0];
    },
    //newTopicData를 매개변수로 받아 DB에 데이터를 추가한 후, 해당 데이터의 insertId 반환
    createTopic: async (newTopicData) => {
        const query = 'INSERT INTO Topics(title, content) VALUES(?, ?);';
        const result = await db.query(query, [newTopicData.title, newTopicData.content]);
        return result[0].insertId;
    },
    deleteTopic: async (topicId) => {
        const query = 'DELETE FROM Topics WHERE topic_id=?;';
        await db.query(query, [topicId]);
    },
    updateTopic: async (newTopicData, topicId) => {
        const query = 'UPDATE Topics SET title=?, content=? WHERE topic_id=?;';
        await db.query(query, [newTopicData.title, newTopicData.content, topicId]);	//Topics의 topicId에 해당하는 데이터 업데이트 
    }
}

 

>> 업데이트 버튼 정상적으로 생김

 

>> 정상적으로 업데이트됨

'대딩코딩 > 웹개발 스터디' 카테고리의 다른 글

[Express] 14. Create Comment POST  (0) 2023.12.01
[Express] 13. Routing  (0) 2023.12.01
[Express] 11. Delete Topic POST  (0) 2023.12.01
[Express] 10. Create Topic POST  (0) 2023.12.01
[Express] 9. Create Topic GET  (0) 2023.12.01