tech.junha.kr

노트/JavaScript

fetch

작성 수정

0. Quick Review

GET

fetch('/data.json')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })

POST

fetch(url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(data => {
        console.log(data)
     })

1. fetch API란?

  • fetch() 함수는 기존 XMLHTTPRequest를 대체하는 ES6 HTTP 요청 API이다.
  • 네트워크 요청 성공 시, Response 객체를 resolve한 Promise를 리턴한다.
  • 네트워크 요청 실패 시, reject한 Promise를 리턴한다.
let result = fetch(serverURL);
result
  .then((response) => {
    if (response.ok) {
      // 요청 성공.
    }
  })
  .catch((error) => {
    // 요청 실패.
  });

2. Response 객체

  • Response 객체는 결과에 대한 다양한 정보를 담는다.
  • response.ok는 HTTP Status code가 200-299 사이면 true, 그 외 false이다.
  • response.status는 HTTP status code를 담는다.
  • response.url은 요청한 URL 정보를 담는다.
  • response.headers로 Response 객체의 헤더 정보를 얻을 수 있다.
fetch(serverURL).then((response) => {
  response.ok;
  response.status;
  response.statusText;
  response.url;
  response.bodyUsed;
  response.header
});

3. body 정보 읽기

  • Promise가 resolve 되면 얻어온 body 정보를 읽는다.
  • Response 객체에는 프라미스를 기반으로 하는 다양한 메서드가 있다.

response.json()

  • 객체로 resolve하며 Promise를 반환한다.
fetch(serverURL)
  .then((response) => {
    return response.json();
  })
  .then((json) => {
    console.log('body : ', json);
  });
  • response.text(), response.blob(), response.formData() 등의 메서드로 다른 형태의 바디를 읽을 수 있다.
  • 이 메서드들을 사용하면 다양한 형태의 response의 body를 처리할 수 있다.

4. POST 요청

  • fetch(url, options) 로, fetch 메서드 옵션을 넣는다.
  • method 필드로 여러 요청 메서드를 활용한다.
  • headers, body 필드를 활용해 서버에 추가 정보를 보낸다.
  • body필드에 객체가 들어가면 안된다? => JSON.stringify 를 통해 문자열로 바꾼다.
fetch(serverURL, {
  method: 'post',
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
    Authentication: 'mysecret',
  },
  body: JSON.stringify(formData),
})
  .then((response) => {
    return response.json();
  })
  .then((json) => {
    console.log('POST 요청 결과:', json);
  });