수정했으니 삭제해보자

gotcha!!·2024년 1월 30일
0

Nodejs

목록 보기
6/11

이전에 글을 수정하는 것을 해보았다.
이번엔 삭제를 해보자
form태그를 통해서 데이터를 삭제할 수 있지만 새로고침 때문에 화면이 부드럽지 않아 보인다.
그래서 나는 부드러운 화면을 위해서 ajax를 통해서 새로고침 없이 글을 삭제할 것이다.

삭제

list.ejs

<div class="white-bg">
       <% for(let i = 0; i < posts.length; i++){ %>
            <div class="list-box" id="post_<%= posts[i]._id %>">
                <h4>
                    <a href="/detail/<%= posts[i]._id %>"><%= posts[i].title %></a>
                </h4>
                <p><%= posts[i].content %></p>
                <span class="delete" style="cursor: pointer;">글 삭제하기</span>
            </div>
        <% } %>
    </div>

list.ejs에서 디비에 글 데이터들을 받아와서 쭉 나열한 상태이다.
span태그의 삭제 버튼을 통해서 글의 아이디를 서버로 보내서 글을 삭제할 것이다.
서버로 데이터를 전송할 수 있는 방법은 body에 담아서 보내기, query string, url parameter가 있는데
나는 body에 담는 방법을 선택했다.

<script>
        '<% for(let i = 0; i< posts.length; i++){ %>'
                document.querySelectorAll('.delete')['<%= i %>'].addEventListener('click', () => {
                let id = '<%= posts[i]._id %>'
                
                fetch('/delete', {
                    method: 'DELETE',
                    headers: {'Content-Type' : 'application/json'},
                    body : JSON.stringify({_id : id})
                })
                .then(resp =>{
                    if(resp.ok){
                        document.getElementById('post_<%= posts[i]._id %>').remove()
                    }else{
                        console.error('삭제 실패')
                    }
                })
                .catch(err =>{
                    console.error('네트워크 오류', err);
                })
            })
        '<%} %>'
    </script>
    
    
    
    server.js
    
    app.delete('/delete', async (req, resp) =>{
    try{
        let id = req.body._id;
        if(id == null){
            resp.status(400).send('오류!!!!')
        }else{
            await db.collection('post').deleteOne({_id : new ObjectId(id)})
            resp.send('삭제완료')
        }
        
    }catch(e){
        console.log(e)
        resp.status(500).send('Delete Error!')
    }
})

바디에 담아 바디에 있는 데이터를 서버에서 변수에 담아준 뒤, db측에 그 id에 맞는 데이터를 삭제하도록 하였다.
그리고, 삭제가 끝나면 새로고침이 없는 게 장점인 ajax통신이기에, redirect, render를 통해서 새로고침을 하는 것이 아니라, 해당 html을 삭제하도록 코드로 담아보았다.

profile
ha lee :)

0개의 댓글