프로그래밍 언어/JavaScript

자바스크립트 네트워크 Fetch API와 비동기 처리 가이드 - 자바스크립트 #11

eco7T 2024. 7. 26. 08:51
반응형

이번에는 자바스크립에서 네트워크 요청을 조금 더 쉽게 처리할 수 있도록 하는 Fetch API의 사용법에 대해 살펴봅니다. 비동기 처리의 개념을 다시 한번 다뤄보며 XMLHttpRequest와 비교하여 Fetch API를 이해하면 좋을 것 같습니다.

자바스크립트 네트워크 Fetch API
자바스크립트 네트워크 Fetch API

 

Fetch API

Fetch API는 웹 브라우저에서 서버와 네트워크 요청을 주고받을 때 사용하는 인터페이스입니다. 이 API를 사용하면 웹 페이지에서 서버로 데이터를 요청하거나 서버에 데이터를 전송하는 작업을 쉽게 수행할 수 있습니다.

 

Fetch API가 등장하기 전에는 주로 XMLHttpRequest(XHR)라는 객체를 사용했습니다. 하지만 Fetch API는 XHR보다 더 강력하고 유연하며 사용하기 쉽습니다. 또한 Promise 기반으로 동작하기 때문에 비동기 처리를 더욱 편리하게 할 수 있습니다.

비동기 처리

비동기 처리란 특정 코드의 실행이 완료될 때까지 기다리지 않고 다음 코드를 실행하는 자바스크립트의 특성을 말합니다. 이는 웹 페이지의 반응성을 높이고 사용자 경험을 개선하는 데 중요한 역할을 합니다.

 

  Fetch API 기본 사용법

Fetch API의 가장 기본적인 사용법은 다음과 같습니다.

fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));

이 코드를 하나씩 자세히 살펴보겠습니다.

  1. fetch('https://api.example.com/data')
    • fetch() 함수를 호출하여 네트워크 요청을 시작합니다.
    • 괄호 안의 URL은 데이터를 요청할 서버의 주소입니다.
  2. .then(response => response.json())
    • 서버로부터 응답이 오면 이 부분이 실행됩니다.
    • response.json()은 서버의 응답을 JSON 형태로 파싱(해석)합니다.
    • JSON(JavaScript Object Notation)은 데이터를 주고받을 때 자주 사용되는 데이터 형식입니다.
  3. .then(data => console.log(data))
    • JSON으로 파싱된 데이터를 받아 처리하는 부분입니다.
    • 여기서는 간단히 콘솔에 출력하고 있습니다.
  4. .catch(error => console.error('Error:', error))
    • 요청 과정에서 오류가 발생하면 이 부분이 실행됩니다.
    • 오류 내용을 콘솔에 출력합니다.
반응형

  Fetch API의 상세 기능

요청 옵션 설정

Fetch API는 두 번째 인자로 옵션 객체를 받을 수 있습니다. 이를 통해 요청 방법(GET, POST 등), 헤더, 본문 등을 설정할 수 있습니다.

fetch('https://api.example.com/data', { method: 'POST', // HTTP 요청 방법 headers: { 'Content-Type': 'application/json', // 요청 헤더 설정 'Authorization': 'Bearer YOUR_TOKEN_HERE' // 인증 토큰 설정 (필요한 경우) }, body: JSON.stringify({ // 요청 본문 설정 key1: 'value1', key2: 'value2' }) }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
  • method: HTTP 요청 방법을 지정합니다. 'GET', 'POST', 'PUT', 'DELETE' 등이 가능합니다.
  • headers: 요청 헤더를 설정합니다. 'Content-Type'은 보내는 데이터의 형식을 서버에 알려줍니다.
  • body: 서버로 보낼 데이터입니다. JSON.stringify()를 사용해 자바스크립트 객체를 JSON 문자열로 변환합니다.

응답 처리

서버로부터 받은 응답(Response 객체)은 다양한 메서드를 제공합니다.

fetch('https://api.example.com/data') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } console.log('Status:', response.status); console.log('Status Text:', response.statusText); console.log('Content-Type:', response.headers.get('Content-Type')); return response.json(); }) .then(data => console.log('Data:', data)) .catch(error => console.error('Error:', error));

response.ok: 응답 상태가 200-299 사이면 true입니다.

response.status: HTTP 상태 코드를 반환합니다(예: 200, 404, 500 등).

response.statusText: 상태 메시지를 반환합니다(예: "OK", "Not Found" 등).

response.headers: 응답 헤더에 접근할 수 있습니다.

 

다양한 데이터 형식 처리

서버로부터 받은 데이터는 여러 형식으로 처리할 수 있습니다.

fetch('https://api.example.com/data') .then(response => { const contentType = response.headers.get('Content-Type'); if (contentType && contentType.includes('application/json')) { return response.json(); } else if (contentType && contentType.includes('text/plain')) { return response.text(); } else if (contentType && contentType.includes('image/')) { return response.blob(); } else { throw new Error('Unsupported content type'); } }) .then(data => console.log('Data:', data)) .catch(error => console.error('Error:', error));
  • response.json(): JSON 형식의 데이터를 파싱 합니다.
  • response.text(): 텍스트 형식의 데이터를 반환합니다.
  • response.blob(): 이미지나 파일 등의 바이너리 데이터를 처리합니다.

  Fetch API의 고급 기능

AbortController를 이용한 요청 취소

때로는 실행 중인 Fetch 요청을 취소해야 할 필요가 있습니다. 이럴 때 AbortController를 사용할 수 있습니다.

const controller = new AbortController(); const signal = controller.signal; fetch('https://api.example.com/data', { signal }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => { if (error.name === 'AbortError') { console.log('Fetch aborted'); } else { console.error('Error:', error); } }); // 1초 후에 요청 취소 setTimeout(() => controller.abort(), 1000);
  • AbortController를 생성하고, 그 signal을 fetch 옵션으로 전달합니다.
  • controller.abort()를 호출하면 진행 중인 fetch 요청이 취소됩니다.
  • 요청이 취소되면 AbortError가 발생하며, 이를 catch 블록에서 처리할 수 있습니다.

 

Fetch API와 async/await 사용

Fetch API는 Promise를 반환하기 때문에 async/await 문법과 함께 사용하면 코드를 더 간결하고 읽기 쉽게 만들 수 있습니다.

async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error); } } fetchData();

이 방식의 장점은,

  • .then() 체인을 사용하지 않아 코드가 더 선형적이고 읽기 쉽습니다.
  • 오류 처리를 위해 try-catch 블록을 사용할 수 있어 더 자연스럽습니다.
반응형