Backend
home
🖋️

8일차

생성일
2024/07/18 14:48
태그
본 프로젝트는 “스프링부트 3 백엔드 개발자 되기” 서적을 참고하여 진행하였음

생성 기능 마무리

article.js 에 코드 작성
article.js 파일을 열어 [등록] 버튼을 누르면 입력 칸에 있는 데이터를 가져와 게시글 생성 API에 글 생성 관련 요청을 보내준다.
id가 create-btn인 엘리먼트를 찾아 그 엘리먼트에서 클릭 이벤트 발생 시 id가 title, content인 엘리먼트의 값을 가져와 fetch() 메서드를 통해 생성 API로 /api/articles/ POST 요청을 보낸다.
// 생성 기능 const createButton = document.getElementById("create-btn"); if (createButton) { // 클릭 이벤트 감지 시 생성 API 요청 createButton.addEventListener("click", (event) => { fetch("/api/articles", { method: "POST", headers: { "Content-Type": "application/json", }, body: JSON.stringify({ title: document.getElementById("title").value, content: document.getElementById("content").value, }), }).then(() => { alert("등록 완료되었습니다."); location.replace("/articles"); }) }) }
JavaScript
복사
articleList.html 파일 수정
<div class="container"> <!-- 추가 --> <button type="button" id="create-btn" th:onclick="|location.href='@{/new-article}'|" class="btn btn-secondary btn-sm mb-3">글 등록</button> <!-- // --> <div class="row-6" th:each="item : ${articles}"> <div class="card"> <div class="card-header" th:text="${item.id}"> </div> <div class="card-body"> <h5 class="card-title" th:text="${item.title}"></h5> <p class="card-text" th:text="${item.content}"></p> <a th:href="@{/articles/{id}(id=${item.id})}" class="btn btn-primary">보러가기</a> </div> </div> <br> </div> </div>
HTML
복사
결과 확인