fetch()

.esc·2021년 2월 16일
1

fetch API

fetch함수를 사용하여 데이터를 비동기로 요청할 수 있다.

  • AJAX
    (Asynchronous JavaSctipt And XML, 비동기적 자바스크립트와 XML)
    비동기 HTTP 요청 기술을 나타내는 용어

  • JSONplaceholder
    https://jsonplaceholder.typicode.com/
    예제에서는 Fake REST API를 사용한다.

GET

fetch함수의 기본은 GET으로 간단하게 사용할 수 있다.

  • 첫번째 then: 요청이 성공할 경우 response객체를 받아 json형태로 파싱
  • 두번째 then: json형태의 응답 body의 데이터를 출력
  • catch: 요청이 완료되지 못할 때 에러 처리
fetch('https://jsonplaceholder.typicode.com/users')
  .then(res => res.json())
  .then(data => console.log(data))
  .catch(err => console.log('Fetch err', err));
  • await async와 함께 사용
async function getUsers() {
  let res = await fetch('https://jsonplaceholder.typicode.com/users');
  let data = await res.json();
  console.log(data);
}
  • 응답 header내용을 추출할 수 있다.
for (let [key, value] of res.headers) {
  console.log(`${key} = ${value}`);
}

POST

POST의 경우 fetch함수의 두번째 인자에 methodbody정보를 넘겨야 한다.

  • headers: json을 전송하기 때문에 Content-Typeapplication/json으로 설정한다.
  • body: JSON.stringify()함수를 사용하여 json형태로 전달한다.
fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
  body: JSON.stringify({
    name: 'foo',
    username: 'bar',
  }),
})
  .then(res => res.json())
  .then(data => console.log(data))
  • await async와 함께 사용
async function getUsers() {
  let res = await fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
  body: JSON.stringify({
    name: 'foo',
    username: 'bar',
  }),
});
  let data = await res.json();
  console.log(data);
}

PUT

  • 리소스를 update
fetch('https://jsonplaceholder.typicode.com/users', {
  method: 'PUT,
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
  body: JSON.stringify({
    name: 'foo',
    username: 'bar',
  }),
})
  .then(res => res.json())
  .then(data => console.log(data))

정리

  1. fetch함수를 호출하면 브라우저는 요청을 보내고 promise객체를 반환한다.
  2. 요청이 완료되면 성공여부에 상관없이 promise가 resolved되어 response객체가 반환된다.
  3. response객체는 ok, status프로퍼티를 이용하여 응답 성공 여부를 확인할 수 있다.
  4. http요청이 완료되지 못한 상태라면 promise가 rejected된다. 이 경우 catch함수를 사용하여 에러를 처리한다.
  • fetch의 기본 문법
    - url: 접근하고자 하는 url
    - options: 선택 매개변수, methodheader 등을 지정
fetch(url, [options])
  .then(response => response.json())
  .then(result => /* result 출력 */);
  
// ES5
fetch(url, [options])
  .then(function(response) {
    return response.json();
  })
  .then(function(result) {
    return /* result 출력 */
  });
  • await async를 함께 사용할 경우에는
async function getResult() {
  let response = await fetch(url, [options]);
  let result = await response.json();
  /* result 출력 */
};
  • response객체의 프로퍼티
    - response.status: http 상태 코드
    - response.ok: 응답 상태가 200~299일 경우 true
    - response.headers: http 헤더
  • fetch의 옵션
    - method: http 메서드
    - headers: 요청 헤드가 담긴 객체
    - body: 보내려는 데이터(요청 본문)

참조

https://jsonplaceholder.typicode.com/
https://hogni.tistory.com/142
https://yeri-kim.github.io/posts/fetch/
https://ko.javascript.info/fetch

profile
front-end

0개의 댓글