Fetch API

홍준섭·2022년 8월 22일

개발 공부

목록 보기
1/20

기본 개념과 사용 방법

fetch에는 일반적인 오브젝트로 request와 response가 포함되어 있다. 또한 CORS나 HTTP 오리진 헤더의 행동에 관련한 개념에 대해서도 정의되어 있다. fetch()를 불러들이는 경우, 취득할 리소스를 반드시 인수로 지정하지 않으면 안된다. fetch()는 promise객체를 반환. 리퀘스트가 성공하든 실패하든 해당 리퀘스트 통신에 대한 response객체가 취득된다. fetch()의 두번째 인수는 초기화에 사용되는 객체를 정의하고 있다.

기본적인 fetch 요청

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

요청 옵션 사용하는 경우

	async function postData(url = '',data={}){
      const response = await fetch(url,{
        method: 'POST',
        mode: 'cors',
        cache: 'no-cache',
        credentials: 'same-origin',
        headers: {
          'Content-Type':
        },
        redirect: 'follow',
        referrerPolicy: 'no-referrer',
        body: JSON.stringfy(data),
      });
      return response.json();
    }

	postData('https://example.com/answer',{answer:42}).then((data) =>{
      console.log(data);
    });

fetch의 성공 여부 확인

fetch('flowers.jpg')
  .then((response) => {
    if (!response.ok) {
      throw new Error('네트워크 응답이 올바르지 않습니다.');
    }
    return response.blob();
  })
  .then((myBlob) => {
    myImage.src = URL.createObjectURL(myBlob);
  })
  .catch((error) => {
    console.error('fetch에 문제가 있었습니다.', error);
  });
profile
개발 공부중입니다

0개의 댓글