Fetch api란?

Jonghyeon·2021년 8월 21일
1
post-thumbnail

fetch api

  • 비동기 http요청을 좀 더 쓰기 편하게 해주는 API
  • XMLHTTPRequest을 대체
  • Promise 기반 동작
fetch('https://jonghyeon.com/todos')
  .then((res) => {
    return res.json();
  })
  .then((todos) => {
    // todos 조회 완료!
    console.log(todos);
  });

사용하기

Response에는 text, json 외에도 아래와 같은 method들이 있습니다.

Response.arrayBuffer()
Response.blob()
Response.clone()
Response.error()
Response.formData()
Response.json()
Response.redirect()
Response.text()

Response MDN 참고하기

주의 사항

fetch는 HTTP error가 발생하더라도 reject 되지 않습니다.
네트워크 에러나 요청이 완료되지 못한 경우에만 reject 됩니다.

그러므로 서버 요청 중 에러가 생겼을 경우에도 then으로 떨어지므로 response의 status code나 ok를 체크해주는 것이 좋습니다.

존재하지 않는 api 호출로 테스트하기

res.ok는 status가 200~299 사이인 경우 true가 됩니다.

fetch('https://jonghyeon.com/todos-undefined-api')
  .then((res) => {
    if (res.ok) {
      // 이 구문이 있어야 서버 요청 중 에러가 생겼을 경우를 체킹할 수 없다.
      return res.json();
    } else {
      throw new Error('요청이 처리되지 못함');
    }
  })
  .then((result) => console.log(result))
  .catch((e) => alert(e.message));

fetch의 두 번째 인자로 옵션을 줄 수 있습니다.

const headers = new Headers();
headers.append('x-auth-token', 'TOKEN');
fetch('https://jonghyeon.com/product', {
  method: 'POST',
  headers,
  body: JSON.stringify(product),
});
profile
종현

0개의 댓글