[JS] json-server / fetch API 사용하기

TATA·2022년 12월 4일
0

JavaScript

목록 보기
1/25

json-server란?

json-server는 짧은 시간에 REST API를 구축해 주는 패키지이다.
프로덕션 전용은 아니고, 프로토타입을 만들거나 공부를 하기 위해 서버가 필요할 때 사용하면 좋은 도구이다.

JSON 서버 설치하기

npm을 통해 글로벌로 설치하기

npm install -g json-server

JSON 서버 시작

다음 명령어를 통해 서버를 실행

json-server --watch db.json --port 3001

Routes

다른 경로를 추가할 수도 있다.

GET    /posts
GET    /posts/1
POST   /posts
PUT    /posts/1
PATCH  /posts/1
DELETE /posts/1

예시)
fetch(`${주소}/${페이지id}`)

Paginate

limit: 한 페이지 당 나타낼 데이터의 갯수
(정하지 않으면 기본적으로 10개의 항목이 반환)

GET /posts?_page=7
GET /posts?_page=7&_limit=20

예시)
fetch(`${주소}?_page=${현재페이지}&_limit=${limit}`)

Javacript fetch API란?

AJAX 요청을 하기 위한 기술이다.
(*AJAX란 서버에서 추가 정보를 비동기적으로 가져올 수 있게 해주는 포괄적인 기술을 나타내는 용어)

fetch API 사용법

fetch api의 response는 실제 json 이 아니다.
때문에 fetch api에서는 추가 메서드를 호출해 응답 본문을 받을 필요가 있다. (.json())
(axios는 이 과정을 자동으로 해주기에 바로 response를 받을 수 있다)
body 데이터 타입은 헤더의 content-type 헤더와 일치해야 한다.

기본적인 Fetch 요청

fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));
  .catch((error) => console.error(error));

요청 옵션 제공

fetch() 메서드에는 선택적으로 두 번째 매개변수도 제공할 수 있다.

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // 또는 'PUT', 'GET'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then((response) => response.json())
.then((data) => {
  console.log('성공:', data);
})
.catch((error) => {
  console.error('실패:', error);
});

json-server 참고 링크
https://github.com/typicode/json-server

Fetch API 참고 링크
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

profile
🐾

0개의 댓글