스프링 부트3 제 17장
REST API 요청을 웹 브라우저에서 바로 한다고요?
스프링 부트3 제 17장
뷰 페이지
comments/_new.mustache
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<div class="card m-2" id="comments-new">
<div class="card-body">
<!-- 댓글 작성 폼 -->
<form>
<!-- 닉네임 입력 -->
<div class="mb-3">
<label for="new-comment-nickname" class="form-label">닉네임</label>
<input type="text" class="form-control" id="new-comment-nickname">
</div>
<!-- 내용 입력 -->
<div class="mb-3">
<label for="new-comment-body" class="form-label">내용</label>
<textarea type="text" rows="3" class="form-control" id="new-comment-body"></textarea>
</div>
<!-- 히든 인풋(부모 게시글의 id) -->
{{#article}}
<input type="hidden" id="new-comment-article-id" value="{{id}}">
{{/article}}
<!-- 전송 버튼 -->
<button type="button" class="btn btn-primary" id="comment-create-btn">댓글 작성</button>
</form>
</div>
</div>
<script>
{
const commentCreateBtn = document.querySelector("#comment-create-btn");
commentCreateBtn.addEventListener("click", function() {
// 새 댓글 객체 생성
const comment = {
nickname: document.querySelector("#new-comment-nickname").value, // 새 댓글의 닉네임
body: document.querySelector("#new-comment-body").value, // 새 댓글의 본문
articleId: document.querySelector("#new-comment-article-id").value, // 부모 게시글의 id
};
console.log(comment);
// fetch(): 비동기 통신을 위한 API
const url = "/api/articles/" + comment.articleId + "/comments";
fetch(url, {
method: "POST", // POST 요청
headers: {
"Content-Type": "application/json", // 전송 본문의 데이터 타입 정보(JSON)
},
body: JSON.stringify(comment) // comment 객체를 JSON 문자열로 변환해 전송
}).then(response => {
// HTTP 응답 코드에 따른 메시지 출력
const msg = (response.ok) ? "댓글이 등록됐습니다" : "댓글 등록 실패";
alert(msg);
// 페이지 새로 고침
window.location.reload();
});
});
}
</script>
웹 페이지에서도 자바스크립트를 활용하면 REST API를 호출할 수 있다.
자바스크립트의 querySelector() 메서드를 더 알고 싶다면 여기를 참조하자.
자바스크립트에서 객체를 만드는 방법은 세 가지이다. 객체 리터럴 방식, 생성자 함수 방식, Object.create() 방식이 있다. 여기선 객체 리터럴 방식으로, 객체를 변수로 선언해 사용했다.
fetch() 메서드는 웹 페이지에서 HTTP 통신을 하는 데 사용한다. 요청을 보내고 응답을 받으면 then(response => {})로 응답도 처리할 수 있다.
여기서 response는 API 요청을 보내고 받은 응답 객체이다.
fetch() 메서드에 대해 더 알고 싶다면 여기를 참조하자.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.