sogno
카테고리
작성일
2022. 11. 14. 17:01
작성자
sognociel
  • JSON이란?
  • Fetch API
  • Fetch API - GET, POST, PUT, DELETE

 

 

01. JSON(JavaScript Object Notation)

클라이언트와 서버 간의 HTTP 통신을 위한 텍스트 데이터 포맷. 대부분의 프로그래밍 언어에서 사용 가능하며 키와 값으로 구성

 

JSON.stringify() | 객체 또는 배열을 JSON 포맷의 문자열로 변환

※ 직렬화(serializing) | 클라이언트가 서버로 객체를 전송하려면 객체를 문자열화 해야 하는데, 이를 직렬화라고 함

const obj = {
  name: "Park",
  age: 20,
  alive: true,
  hobby: ["sleeping", "animation"],
};

const json = JSON.stringify(obj);
console.log(json);

 

 

※ JSON.parse() | JSON 포맷의 문자열을 객체로 변환

※ 역직렬화(deserializing) | 서버로부터 클라이언트에게 전송된 JSON 데이터는 문자열타입. 이 문자열을 객체로 사용하려면 JSON 포맷의 문자열을 객체화해야 하는데, 이를 역직렬화라고 함

직렬화와 역직렬화

 

 

 

02. Fetch API

  • 요청과 응답 등의 요소를 자바스크립트에서 접근하고 조작할 수 있는 인터페이스를 제공
  • fetch() 메서드로 네트워크의 리소스를 쉽게 비동기적으로 가져 올 수 있음
// url : 실제 요청할 데이터가 있는 경로, option : 생략 가능

fetch(url, options)
  .then(response => console.log(response)) // 요청을 했으면 응답을 받아야 한다.
  .catch(error => console.log(error)); // 오류가 났을 때

 

fetch 실습

let response = fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => console.log(response))
  .catch((error) => console.log(error));

위 코드의 결과

 

하지만 response 객체는 HTTP 응답 상태(status), HTTP 응답 헤더(headers), HTTP 응답 전문(body) 등을 포함한다.

따라서 실제 내용을 뽑아내려면 JSON 문자열 형태로 변환을 해줘야 처리가 가능하다. (response -> JSON 형태로 파싱)

let response = fetch("https://jsonplaceholder.typicode.com/todos/1")
  .then((response) => response.json()) // json 형태로 파싱
  .then((data) => console.log(data)) // 파싱한 내용을 data에 담음
  .catch((error) => console.log(error));

파싱 결과물

 

 

 

03. json-server

json 파일을 사용하여 간단한 테스트를 위한 REST API server를 구축할 수 있는 패키지

json-server를 사용하려면 node.js가 설치되어 있어야 한다.

$ npm install -g json-server
$ json-server --watch 파일명 --port 포트번호

※ json 파일이 담겨있는 폴더에서 watch를 해야 데이터를 볼 수 있다.

json 파일이 없는 폴더에서 실행했을 때
json 파일이 있는 폴더에서 실행했을 때 제대로 불러오는 모습을 볼 수 있다.

 

 

json-server를 이용하여 crud(Create, Read, Update, Delete) 알아보기

서버에서 데이터를 받아오는 것은 비동기 방식이며 해당 데이터를 직렬화하거나 역직렬화하는 방법이 중요하다.

직렬화와 역직렬화에 대한 정의는 해당 페이지 위쪽에서 확인할 수 있다.

 

 

  • Read | method는 GET
// 데이터 조회
const getData = async () => {
  let response = await fetch(`http://localhost:5000/books/`);
  let data = await response.json();
  bookData = [...data];
  console.log(bookData);
};
// getData();

// 데이터 하나 조회
const getDataOne = async (id) => {
  let response = await fetch(`http://localhost:5000/books/${id}`);
  let data = await response.json();
  bookDataOne = data;
  console.log(bookDataOne);
};
// getDataOne(1);

 

  • Create | method는 POST

매개변수로 객체를 받아오고, 해당 객체를 직렬화(문자화) 시켜 서버로 넘겨주게 된다. 아래 코드는 함수를 호출할 때 객체를 하드코딩으로 넣어주었지만, 객체를 따로 저장하여 보내는 방법도 있다.

// 데이터 생성
const createData = async (data = {}) => {
  let response = await fetch(`http://localhost:5000/books/`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
  return response.json();
};
// createData({ id: 200, name: "aaa", age: 80 });

 

객체를 따로 저장하여 매개변수로 보내는 방법

// 책 정보를 form 태그에 입력하면 추가하는 함수
const createData = async (data = {}) => {
  let response = await fetch(`http://localhost:5000/books/`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
  return response.json();
};

// 폼 태그에 addEventListener
// submit을 하면 새로고침이 되기 때문에 preventDefault로 막아준다
// 객체를 만드는 함수로 나온 obj를 createData의 매개변수로 넘겨준다
// 넘겨준 후 json-server에서 데이터를 받고, getData내부의 showList로 다시 새롭게 표를 출력해준다.
$form.addEventListener("submit", function (e) {
  e.preventDefault();
  const bookInfo = document.querySelectorAll('input[type="text"]');
  const obj = {
    id: document.querySelectorAll("tr").length,
    title: bookInfo[0].value,
    publisher: bookInfo[1].value,
    price: bookInfo[2].value,
  };
  bookInfo.forEach((item) => (item.value = ""));
  createData(obj);
  getData();
});

 

  • Update | method는 PUT
// 데이터 수정
const updateData = async (data = {}) => {
  let response = await fetch(`http://localhost:5000/books/${data.id}`, {
    method: "PUT",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(data),
  });
  return response.json();
};
// updateData({ id: 1, name: "Kim2", age: 14 });

 

  • Delete | method는 DELETE
// 데이터 삭제
const deleteData = async (id) => {
  let response = await fetch(`http://localhost:3000/userInfo/${id}`, {
    method: "DELETE",
  });
  return response.json();
};
// deleteData(200);

 

update와 delete 또한 사용자의 입력값을 받아 함수의 매개변수로 넣어주는 방식으로 사용할 수 있다.

※ create와 update의 경우 headers: { "Content-Type": "application/json", } 를 추가해 주어야 한다고 하니 주의할 것

 

Content-Type이란?

api요청 시 request에 실어 보내는 데이터(body)의 type정보를 말한다.

"Content-Type": "application/json"은 RestAPI를 사용하게 되며 request를 보낼 때 대부분 json을 많이 사용하게 됨에 따라 자연스럽게 사용이 많이 늘게 되었다고 한다. { key: value } 의 형태로 전송된다는 것을 알려주는 기능이라 생각하면 될 것 같다.

 

 

 

'새싹DT 기업연계형 프론트엔드 실무 프로젝트 과정 5주차 블로그 포스팅'