[자바스크립트] 블로그 글쓰기 (9)

fetch 로 데이터 요청과 응답 받기
Sep 01, 2024
[자바스크립트] 블로그 글쓰기 (9)
자바스크립트로 글쓰기 기능을 만들어보자.

블로그 글쓰기 기능 만들기

 
제네릭<>의 타입은 new 할 때 넣어주면 결정된다.
ex. new ApiUtil<>(board); → 들어오는 board 의 타입에 따라 결정된다.
notion image
notion image
 
모든 데이터는 자기 언어가 아니라 JSON 으로 바꿔서 보내야 하며,
받을 때도 물론 JSON 으로 바꿔서 받아야 한다.
 

<form> 태그 수정

 
이제는 form 태그로 보낼 것이 아니라서 폼태그의 name 을 id 로 바꾼다.
JSON 은 form 지원을 하지 않기 때문이다.
이제 자바스크립트에서 CSS 선택자를 사용하여 document.querySelector(’#id’); 로 사용 할 것.
 
notion image
 
그리고 폼 태그의 버튼을 누르면 자동으로 submit 으로 액션이 실행되기 때문에 이것을 바꿔주어야 한다.
notion image
폼 태그의 액션 발동하면서 데이터 전송하게 되는데 → 액션이 발동해서 새로 업로드가 된다.
액션이 발동하면 안되니까
<button type="button" ~~~> 으로 바꿔주는 것이 중요하다.
notion image
 

<script> 기능 넣기

 
notion image
1. #id 로 값을 꺼내어, 객체로 만들어서
→ 2. JSON 으로 만들고
→ 3. fetch 로 전송
notion image
 

1. DOM 에서 값 가져오기

닫는 태그(ex. <div>)안의 공간은 text() 메서드로 가져온다.
<input> 태그처럼 value 속성이 있는 태그들은 val() 메서드로 값을 가져온다.
자바스크립트 객체 모양새
// 1. DOM 에서 값 가져오기 let board = { title: $("#title").val(), content: $("#content").val() }
 

제이쿼리 메서드 참고 링크

notion image
 
진짜 문자열만 가져오고 싶을 때는 text() ,
html 도 들고오려면 html()
샘플 파일 만들어서 실행해보기.
notion image
notion image
notion image

 

2. JSON 으로 변경하기

자바스크립트 객체 → JSON 변경하는 문법
// 2. JSON 으로 변경하기 let reqBody = JSON.springify(board);
 

3. fetch 로 post 요청하기 ★★★★★

 
데이터를 들고 들어갈 때는 content-type 이 반드시 필요하다. (MIME 통신을 표현하는 데이터 타입으로, ex. application/json, application/x-www~~)
내가 들고 가는 데이터의 레이블링이 안되어있으면 받는 쪽에서 어떻게 해야 하는지 모른다.
 
notion image
 

예시)
@RestController 컨트롤러 서버 실행 (기본적으로 @RestController는 JSON 형식으로 데이터를 반환)
return “<h2>hello<h2>” 으로 리턴값을 html 로 하고,
브라우저에서 localhost:8080/hello 실행하면,
notion image
스프링에서 응답의 타입을 결정해서 보내준다. 브라우저에서 Response Content-Type 을 texthtml 로 받아서 보여주는 것이다.
바디 데이터를 줄 때에는 항상 이 데이터가 뭔지 알려주어야 한다.
기본기다.
notion image
 
notion image
@RequestMapping(value = "/hello", method = RequestMethod.GET, produces = "text/plain") public String hello(){ return "<h1>hello</h1>"; }
notion image
 

 

fetch 문법 정리 참고 링크

notion image
 
 
notion image
notion image
fetch 의 key 값들을 정리하고(method, body, headers…),
MIME 타입 정리하고,
MIME 타입 공식홈페이지 들어가서 보고~
GPT 한테 뭔지 물어보고~
이렇게 공부해야 한다. 헥헥

 
async<>await 둘은 세트
notion image
 
fetch 함수는 서버로부터의 응답을 response 객체로 반환하고, 이 response 객체는 HTTP 응답의 상태, 헤더, 본문 등의 정보를 포함하고 있다.
response.json() 은 응답 본문을 JSON 형식으로 파싱하여 자바스크립트 객체로 변환한다.
let respBody = await response.json(); // JSON -> 자바스크립트 객체 변환
notion image
notion image
 
콘솔창에서 자바스크립트 객체 모양으로 응답된 것을 확인 할 수 있다.
 
notion image
 

4. 응답 후 처리

location.href = "list.html";
 
글쓰기 기능 코드
<script> async function btnSave() { // 1. dom에서 값 가져오기 let board = { title: $("#title").val(), content: $("#content").val() }; // 2. JSON 으로 변경하기 let reqBody = JSON.stringify(board); // 3. fetch 로 post 요청하기 let response = await fetch("http://localhost:8080/board", { method: "post", body: reqBody, headers: { 'Content-Type': 'application/json; charset=utf-8', } }); let respBody = await response.json(); console.log("respBody", respBody); // 4. 응답 후 처리 location.href = "list.html"; } </script>
 
전체 코드
<!DOCTYPE html> <html lang="en"> <head> <title>Blog</title> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"> </head> <body> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <div class="container-fluid"> <a class="navbar-brand" href="../../../../../../jswork/blog/list.html">Metacoding</a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#collapsibleNavbar"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="collapsibleNavbar"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="save-form.html">글쓰기</a> </li> </ul> </div> </div> </nav> <div class="container p-5"> <!-- 요청을 하면 localhost:8080/board/save POST로 요청됨 title=사용자입력값&content=사용자값 --> <div class="card"> <div class="card-header"><b>글쓰기 화면입니다</b></div> <div class="card-body"> <form> <div class="mb-3"> <input type="text" class="form-control" placeholder="Enter title" id="title"> </div> <div class="mb-3"> <textarea class="form-control" rows="5" id="content"></textarea> </div> <button onclick="btnSave()" type="button" class="btn btn-primary form-control">글쓰기완료</button> </form> </div> </div> </div> <footer class="bg-light p-5 text-center"> <h4>Created by Metacoding</h4> <h5>☎ 010-2222-7777</h5> <button class="btn btn-outline-primary">고객센터</button> <button class="btn btn-outline-primary">오시는길</button> </footer> <script> async function btnSave() { // 1. dom에서 값 가져오기 let board = { title: $("#title").val(), content: $("#content").val() }; // 2. JSON 으로 변경하기 let reqBody = JSON.stringify(board); // 3. fetch 로 post 요청하기 let response = await fetch("http://localhost:8080/board", { method: "post", body: reqBody, headers: { 'Content-Type': 'application/json; charset=utf-8', } }); let respBody = await response.json(); console.log("respBody", respBody); // 4. 응답 후 처리 location.href = "list.html"; } </script> </body> </html>
 
호호 완성.
 
notion image
Share article

eunmouse