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] 14. Create Comment POST 본문

대딩코딩/웹개발 스터디

[Express] 14. Create Comment POST

시데브 2023. 12. 1. 20:39

Comment를 입력받고 웹페이지에 출력

 파일명: 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('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');

app.get('/', homeController.getTopics);

//Routers
const topicRouter = require('./routers/topicRouter.js');
const commentRouter = require('./routers/commentRouter.js');
app.use('/topic', topicRouter); 
app.use('/comment', commentRouter); //'/comment' 형태로 받는 건 전부 commentRouter가 처리

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

>> commentRouter로 이동

 

 파일명: commentRouter.js

const express = require('express');
const router = express.Router();
const commentController = require('../controllers/commentController.js');

router.post('/create/:topic_id', commentController.createComment);

module.exports = router;

>> commentController로 이동

 

 파일명: commentController.js

const commentModel = require('../models/commentModel.js');

module.exports = {
    createComment: async (req, res) => {
        const topicId = req.params.topic_id;
        const newCommentData = req.body;
        await commentModel.createComment(topicId, newCommentData);

        res.redirect(`/topic/read/${topicId}`);
    }
}

>> commentModel로 이동

 

파일명: commentModel.js

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

module.exports = {
	//DB에 comment 정보 추가
    createComment: async (topicId, newCommentData) => {
        const query = 'INSERT INTO Comments(username, content, topic_id) VALUES(?, ?, ?);';
        await db.query(query, [newCommentData.username, newCommentData.content, topicId]);
    },
    //DB에서 comment 정보 read
    getComments: async (topicId) => {
        const query = 'SELECT * FROM Comments WHERE topic_id=?;';
        const comments = await db.query(query, [topicId]);

        return comments[0];
    }
}

 

 

파일명: topic.ejs

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

<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>

<div class="comment-container">
    <% for(let comment of comments) { %>
        <div class="comment-div">
            <div>
                    <p><b><%= comment.username %></b></p>
                    <p><%= comment.content %></p>
            </div>
            <form action="/comment/delete/<%= comment.comment_id %>">
                <button>Delete</button>
            </form>
        </div>
    <% } %>
</div>

<form action="/comment/create/<%= topic.topic_id %>" method="post">
    <input type="text" name="username" class="input-text" placeholder="username...">
    <textarea name="content" id="" class="input-textarea" cols="30" rows="3" placeholder="content..."></textarea>
    <button>Submit</button>
</form>

>> class: comment-div, comment-container에는 입력된 comment 정보 출력, 삭제 정보와는 각각 div, form 태그로 나눠짐

>> class: input-text, 아래에는 comment create

 

 파일명: input.css

.input-text,
.input-textarea {
    display: block;
    margin: 1rem;
}

.comment-div {
    margin: 1rem;
    padding: 1rem 3rem;
    border: 2px solid gray;
    border-radius: 3rem;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
}

>> div에는 comment 내용, form에는 delte가 포함돼있기 때문에 distplay: flex로 둘을 나눌 수 있음

 

 

 

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

[Express] 16. Create Comment Fetch  (0) 2023.12.04
[Express] 15. Delete Comment POST  (0) 2023.12.01
[Express] 13. Routing  (0) 2023.12.01
[Express] 12. Update Topic POST  (0) 2023.12.01
[Express] 11. Delete Topic POST  (0) 2023.12.01