fetch()

2024. 3. 11. 19:19Language/JavaScript

[점프 투 FastAPI] 1-07에서 Svelte 웹 페이지가 FastAPI와 통신할 때 fetch()를 사용한다.

<script>
  let message;

  fetch("http://127.0.0.1:8000/hello").then((response)=>{
    response.json().then((json)=>{
      message = json.message;
    });
  });
</script>

<h1>{message}</h1>

 

json은 많이 들어봤는데 정확한 구조를 오늘 파악해보자.

fetch()가 뭐 하는 메서드인가?

 

참고 : https://ko.javascript.info/fetch

fetch()

  • 리소스를 비동기 요청 가능.
  • 주로 API를 호출하고 응답 데이터를 받아올 때 사용.

 

기본 문법

let promise = fetch(url, [options])

 

url : 접근하고자 하는 URL.
options : 선택 매개변수, method나 header 등 지정.

  • options에 아무것도 지정하지 않으면 GET method로 동작(url로부터 컨텐츠 다운로드).
  • fetch()를 호출하면 브라우저가 네트워크 요청을 보내고 promise가 반환된다. 반환되는 promise는 fetch()를 호출한 코드에서 사용.

 

응답

  • body가 도착하기 전, 서버에서 응답 헤더를 받자마자 요청 처리에 성공했다면 반환받은 promise가 내장 클래스 Response와 함께 이행 상태가 된다.
    • HTTP 응답 프로퍼티가 ok가 아니면(네트워크 문제, 존재하지 않는 사이트 등) promise는 거부 상태.
    • status : HTTP 상태 코드.(200, 404 등..)
    • ok : status가 200~299일 경우 true(boolean).
let response = await fetch(url);

if (response.ok) { // HTTP 상태 코드가 200~299일 경우
  let json = await response.json();
} else {
  alert("HTTP-Error: " + response.status);
}
  • promise를 기반한 Response의 추가 메서드를 호출하여 응답 본문 받기.
    • response.text() : 응답을 읽고 텍스트 반환.
    • response.json() : 응답을 JSON 형태로 파싱.
    • response.formData() : 응답을 FormData 객체 형태로 반환.
    • response.blob() : 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 반환.
    • response.arrayBuffer() : 응답을 ArrayBuffer(바이너리 데이터를 로우 레벨 형식으로 표현) 형태로 반환.
    • response.body : Readable Stream 객체로, 응답 본문을 청크 단위로 읽기.

 

비동기 처리(async, await)

시간이 소요되는 작업이 완료될 때까지 기다리지 않고 따로 처리하며, 일단 다른 코드들이 먼저 실행될 수 있도록 하는 작업. => 순서 보장 X.

let url = 'https://api.github.com/repos/javascript-tutorial/ko.javascript.info/commits';
let response = await fetch(url);

let commits = await response.json(); // 응답 본문을 읽고 JSON 형태로 파싱함

alert(commits[0].author.login);

await : 비동기 작업의 결과값을 얻을 때까지 기다림.

async : await을 함수 내에서 사용할 때 함수 앞에 선언.

 

promise만 사용한다면 then()으로도 가능.

fetch('https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits')
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));

 

POST

GET 이외의 요청은 추가 옵션 사용.

  • method : 'POST'
  • body : 요청 본문으로 다음 중 하나.
    • 문자열(JSON 등) => Content-Type 헤더가 text/plane;charset=UTF-8로 기본 설정.
    • FormData 객체 : form/multipart 형태로 데이터 전송.
    • Blob 또는 BufferSource : 바이너리 데이터 전송.
    • URLSearchParams : x-www-form-urlencoded 형태로 데이터 전송(요즘 잘 안 씀).
  • let user = {
      name: 'John',
      surname: 'Smith'
    };
    
    let response = await fetch('/article/fetch/post/user', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      },
      body: JSON.stringify(user)
    });
    
    let result = await response.json();
    alert(result.message);

 

'Language > JavaScript' 카테고리의 다른 글

Event Loop  (1) 2025.05.09
hoisting  (1) 2025.05.08