fetch() 함수로 원격 API 호출하기

서정준·2022년 7월 3일
0

fetch()란?

fetch()함수를 알기 위해서 API에 대한 이해가 필요합니다.

https://velog.io/@tree0787/API

※ fetch의 사전적 정의

to go to another place to get something or someone and bring it, him, or her back

The global fetch() method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available.

※ promise
https://velog.io/@tree0787/Promises

The promise resolves to the Response object representing the response to your request.

fetch 사용법

fetch() 함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환합니다. 반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject합니다.

Syntax
fetch(url, options)

GET 호출

fetch() 함수는 디폴트로 GET 방식으로 작동하고 GET 방식은 요청 전문을 받지 않기 때문에 옵션 인자가 필요가 없습니다.

fetch("https://jsonplaceholder.typicode.com/posts/1").then((response) =>
  console.log(response)
);

대부분의 REST API들은 JSON 형태의 데이터를 응답하기 때문에, 응답(response) 객체는 json() 메서드를 제공합니다.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json())
  .then((data) => console.log(data));

이 메서드를 호출하면, 응답(response) 객체로 부터 JSON 포멧의 응답 전문을 자바스크립트 객체로 변환하여 얻을 수 있습니다.

POST 호출

method 옵션을 POST로 지정해주고, headers 옵션을 통해 JSON 포멧을 사용한다고 알려줘야 하며, 요청 전문을 JSON 포멧으로 직렬화화여 가장 중요한 body 옵션에 설정해줍니다.

async function postInfo(){

const url = `https://${host}/${path}`;
  const options = {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
	},
    body: JSON.stringify(body),
};

const response = await fetch(url, options).catch(console.error);
}

출처

https://developer.mozilla.org/en-US/docs/Web/API/fetch
https://www.daleseo.com/js-window-fetch/

https://dictionary.cambridge.org/ko/%EC%82%AC%EC%A0%84/%EC%98%81%EC%96%B4/fetch

profile
통통통통

0개의 댓글