본문 바로가기
JavaScript

[JS] Fetch API 사용하기

by watergrace2u 2020. 10. 5.
반응형
SMALL

- fetch() 메서드는 가져오려는 리소스의 경로를 필수 인수로 사용한다.

- 성공 여부와 관계없이 Promise를 반환한다.

- fetch()의 결과로 리턴된 Promise는 HTTP 상태 에러(404, 500인 경우에도)가 발생해도 정상적으로 해결되고(ok상태는 false로 설정됨!) 네트워크 오류가 발생한 경우에만 거부된다. 

ex> 네트워크를 통해 JSON파일을 가져와서 콘솔에 인쇄

fetch('http://example.com/movies.json')
  .then(response => response.json()) // 응답에서 JSON 본문 컨텐츠를 추출하기 위해 json()메서드를 사용한다.
  .then(data => console.log(data));

 

<JSON 인코딩 데이터를 POST할 때 사용하는 방법>

const data = { username: 'example' };

fetch('https://example.com/profile', {
  method: 'POST', // or 'PUT'
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
  console.log('Success:', data);
})
.catch((error) => {
  console.error('Error:', error);
});

 

<가져오기에 성공했는지 확인>

- Response.ok 값이 true인지 확인해야한다.

fetch('flowers.jpg')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.blob();
  })
  .then(myBlob => {
    myImage.src = URL.createObjectURL(myBlob);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

 

<Headers 인터페이스>

- 자신의 헤더를 통해 객체 생성 가능

const myHeaders = new Headers({
  'Content-Type': 'text/plain',
  'Content-Length': content.length.toString(),
  'X-Custom-Header': 'ProcessThisImmediately'
});

- 컨텐츠 조회&검색 가능

console.log(myHeaders.has('Content-Type')); // true
console.log(myHeaders.has('Set-Cookie')); // false
myHeaders.set('Content-Type', 'text/html');
myHeaders.append('X-Custom-Header', 'AnotherValue');

console.log(myHeaders.get('Content-Length')); // 11
console.log(myHeaders.get('X-Custom-Header')); // ['ProcessThisImmediately', 'AnotherValue']

myHeaders.delete('X-Custom-Header');
console.log(myHeaders.get('X-Custom-Header')); // [ ]

 

cf. developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

반응형
LIST

'JavaScript' 카테고리의 다른 글

모던 JS 튜토리얼 정리 1  (0) 2020.11.12
[JS] apply 사용  (0) 2020.10.28
[JS] 클로저 주의사항  (0) 2020.10.28
[JS] async와 await 이해  (0) 2020.10.05
[JS] Promise 이해  (0) 2020.10.05

댓글