fetch api 사용하기 fetch api 사용하기
본문 바로가기
Javascript

fetch api 사용하기

by frontend.chole 2020. 3. 22.

fetch api에 대해서

Fetch API를 사용해 Request나 Response와 같은 HTTP의 파이프라인을 구성하는 요소를 조작하는것이 가능합니다.

ajax를 구현하는 기술에는 여러가지가 있는데  fetch() 메서드를 이용하는 것으로 비동기 네트워크 통신을 보다 쉽게 기술할 수 있습니다.

 

- fetch()로 부터 Promise 객체가 반환됩니다.

- Promise객체는 HTTP error 상태를 reject 하지 않습니다.

- 보통 fetch는 쿠키를 보내거나 받지 않는데 쿠키를 전송하기 위해서는 credentials 옵션을 설정해야합니다.

 

 

fetch api의 기본 사용 문법

fetch('http://example.com/movies.json')
  .then(function(response) {
    return response.json();
  })
  .then(function(myJson) {
    console.log(JSON.stringify(myJson));
  });

인수가 한개일 경우 네트워크에서 JSON 파일을 가져와서 콘솔에 보여주는 코드입니다.

 

 

쿠키를 전송하는 경우 자격증명(credentials)이 포함된 Request 요청

 

1. 자격증명이 포함된 인증서를 보내야할때

fetch('https://example.com', {
  credentials: 'include'  
})

 

 

2. 요청하려는 URL이 호출 스크립트와 동일한 origin을 가지고 있을때만 자격증명을 전송해야할때

fetch('https://example.com', {
  credentials: 'same-origin'  
})

 

 

3. 자격증명을 포함하지 않는것을 원할때

fetch('https://example.com', {
  credentials: 'omit'  
})

 

 

fetch로 JSON인코딩된 데이터를 보내야 하는 경우

const url = 'https://example.com/profile';
const data = {username: 'example'};

fetch(url, {
  method: 'POST', // or 'PUT'
  body: JSON.stringify(data), // data can be `string` or {object}!
  headers:{
    'Content-Type': 'application/json'
  }
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));

 

 

request 객체를 fetch로 전달하기

const myHeaders = new Headers();

const myInit = { method: 'GET',
               headers: myHeaders,
               mode: 'cors',
               cache: 'default' };

const myRequest = new Request('flowers.jpg', myInit);

fetch(myRequest).then(function(response) {
  return response.blob();
}).then(function(myBlob) {
  var objectURL = URL.createObjectURL(myBlob);
  myImage.src = objectURL;
});

 

 

 

댓글