Spring

[Spring / 댓글 비동기요청 #1] _ 22.07.29 [13일차]

양빵빵 2022. 7. 29. 14:48

GET 요청

 

POST 

 

 

DELETE

 

//=================

<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
   
    <div id="reg-form">

        #작성자명 : <input type="text" name ="writer"><br>
        #내용: <input type="text" name="content"> <br>
        <button id="reg-btn">댓글작성</button>

    </div>
   

    <ul id="replies"></ul>

    <script>
        function makeReplyDOM(replyList){
            const $ul = document.getElementById('replies');
            replyList.forEach(rep =>{
                const {replyWriter, replyText, replyNo} = rep;
                const $li = document.createElement('li');

                $li.dataset.rno = replyNo;
               
                $li.textContent = `작성자:' ${replyWriter}, 내용: ${replyText}`;
                const $delBtn = document.createElement('button');
                $delBtn.classList.add('del-btn');
                $delBtn.textContent = '삭제';

                $li.appendChild($delBtn);
                $ul.appendChild($li);

            });

            //삭제버튼 이벤트
            $ul.onclick = e => {
                if(!e.target.matches('.del-btn')) return;

                const rno = e.target.parentElement.dataset.rno;
                fetch(url+'/'+rno,{ method : 'DELETE'})
                .then(res => {
                    if(res.status === 200){ // 통신 성공 여부를 확인
                        return res.text();
                    }
                    return null;
                })
                .then(msg => {
                    if(msg === 'del-success'){
                        alert('삭제 성공!');
                    } else{
                        alert('삭제 실패!')
                    }
                })
                .catch(err => alert('통신 실패!'))
            }

        }
        const boardNo = 301;
        const url = 'http://localhost:8183/api/v1/replies';

        fetch(url + '?boardNo=' + boardNo)
            .then(res => res.json())
            .then(replyMap => {
                makeReplyDOM(replyMap.replyList);
                // console.log(replyMap.replyList[0].replyWriter);
            })


            // 댓글 쓰기 비동기 요청 클릭 이벤트
            document.getElementById('reg-btn').onclick = e => {
                e.preventDefault();
               
                // GET을 제외한 다른 요청방식에는 요청초기화정보객체가 추가필요
                const reqObj = {
                    method:'POST', // 요청 방식 - GET, POST, PUT, DELETE
                    headers:{
                        'content-type' : 'application/json' // 하이픈 특수문자가 들어갈 경우 key를 '' 앞에 작성
                    }, // 요청헤더 정보 - text, json, html, img 인지 등 어떤 데이터인지에 대한 정보

                    body: JSON.stringify({ //json 파일을 js 파일로 변환
                        replyWriter : document.querySelector('[name=writer]').value, // 필드 이름과 똑같이
                        replyText : document.querySelector('[name=content]').value,
                        boardNo : boardNo
                    }) //payload정보 - 서버로 보낼 json 데이터

                };

                //fetch요청 (POST)
                fetch(url,reqObj)
                .then(res=>res.text())
                .then(resultMsg => {
                    console.log(resultMsg);
                    if(resultMsg === 'insert-success'){
                        alert('댓글 등록 성공!');
                    } else {
                        alert('댓글 등록 실패!')
                    }
                })

            }



    </script>
</body>
</html>