[JS/Node] 비동기 (3) - fetch API

선정·2022년 5월 31일
0

Today I Learned

  • Fetch API
    • Fetch 사용하기
    • Axois

Fetch API

Ajax 통신을 할 때 XHR, JQuery, Fetch 등의 API를 사용할 수 있으며 Fetch API는 좀 더 강력하고 유연한 조작이 가능하다. Fetch는 request 및 response 객체와 네트워크 요청과 관련된 다른 요소들도 제공하며 CORS, HTTP Origin header semantics와 같은 개념도 포함하고 있다.

Fetch 사용하기

fetch는 Promise를 기반으로 동작하며, ES6부터 빌트인 API로 제공돼 따로 설치할 필요가 없이 사용할 수 있다.

fetch("https://jsonplaceholder.typicode.com/posts/1")
  .then((response) => response.json()) // Promise 객체 반환
  .then((json) => console.log(json)) // JavaScript 객체 반환
  .catch((error) => console.log(error));

fetch 요청을 보내 서버로부터 성공적으로 응답을 받은 뒤 원하는 데이터를 반환받기 위해서는 response 객체에 json() 메소드를 사용하는 과정을 거쳐야 한다.
.then 구문에 response 객체는 온전하지 않은 stream이다. 아직 데이터를 받는 중이므로 이는 Promise를 반환한다. json() 메소드를 사용하면 이러한 Response stream을 가져와서 끝까지 읽는다. 그리고 다 읽은 body의 텍스트는 JSON으로 파싱한 결과로 담아 Promise로 반환한다.


fetch에서 제공하는 request options

fetch의 첫 번째 매개변수인 resource는 필수 값이며 두 번째 매개변수인 options는 필요 시에 선택적으로 지정하면 된다. method, headers, body 등 다양한 옵션들이 있다.

fetch(resource, options)

// POST 메서드 구현 예제
async function postData(url = '', data = {}) {
  // 옵션 기본 값은 *로 강조
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE 등
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json',
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함
  });
  return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData('https://example.com/answer', { answer: 42 }).then((data) => {
  console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});


Axois

Axios는 node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트이다. Axios는 Fetch API보다 사용이 간편하면서 추가적인 기능들을 포함한다.

Axios는 써드 파티 라이브러리이므로 Fetch API와 달리 별도의 설치가 필요하다. 그리고 .json() 메서드를 사용하지 않아도 자동으로 JSON 데이터로 자동 변환해준다.


axios 설치

npm install axios

요청 메소드 명령어

편의를 위해 지원하는 모든 요청 메소드의 명령어를 제공한다. 명령어 메소드를 사용시 'url', 'method', 'data' 속성을 config에서 지정할 필요가 없다.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])


GET 요청 - Promise

const getPosts = () => {
  axios.get("https://jsonplaceholder.typicode.com/posts/1")
    .then((response) => console.log(response))
    .catch((error) => console.log(error));
}

GET 요청 - Async/Await

const getPosts = async () => {
  try {
    const response = await axios.get("https://jsonplaceholder.typicode.com/posts/1");
    console.log(response);
  } catch(error) {
    console.log(error);
  }
}

POST 요청 - Promise

const data = {
  userId: 101,
  id: 101,
  body: "body content",
  title: "title content"
}

const submitPost = () => {
  axios.post("https://jsonplaceholder.typicode.com/posts", data)
    .then((response) => console.log(response))
    .catch((error) => console.log(error));
}

POST 요청 - Async/Await

const data = {
  userId: 101,
  id: 101,
  body: "body content",
  title: "title content"
}

const submitPost = async () => {
  try {
    const response = await axios.post("https://jsonplaceholder.typicode.com/posts", data);
    console.log(response);
  } catch(error) {
    console.log(error);
  }
}

참고

profile
starter

0개의 댓글