TypeScript에서 Fetch/XMLHttpRequest

TypeScript에서 Fetch/XMLHttpRequest

이 글은 TypeScript에서 Fetch/XMLHttpRequest를 설명합니다.

Fetch APIXMLHttpRequest의 사용법 및 차이점에 대해 배울 수 있습니다.

YouTube Video

TypeScript에서 Fetch/XMLHttpRequest

TypeScript에서는 주로 HTTP 요청을 수행하기 위해 Fetch APIXMLHttpRequest 두 가지 API가 사용됩니다. TypeScript를 사용하면 이러한 API를 사용하여 비동기 통신을 수행할 때 요청 및 응답의 타입 체크를 도입할 수 있어 더 안전한 코드를 작성할 수 있습니다. 아래에서 각 API를 사용하는 방법을 소개하겠습니다.

Fetch API

Fetch API는 비동기 통신(HTTP 요청)을 간단히 수행하기 위해 Promise 기반으로 설계된 API입니다. TypeScript에서는 fetch 메서드를 사용하여 요청을 보내고 타입 안전한 방식으로 응답을 처리할 수 있습니다.

기본 사용법

아래는 GET 요청을 사용하는 기본 예제입니다.

 1const url = 'https://jsonplaceholder.typicode.com/posts';
 2
 3fetch(url)
 4    .then(response => {
 5        if (!response.ok) {
 6        throw new Error('Network response was not ok');
 7        }
 8        return response.json();  // Parse the response as JSON
 9    })
10    .then(data => {
11        console.log(data);
12    })
13    .catch(error => {
14        console.error('Fetch error:', error);
15    });
  • 이 코드는 지정된 URL로 GET 요청을 보내고, 받은 응답을 JSON으로 파싱한 다음 콘솔에 출력합니다.

TypeScript에서 타입 안전한 데이터 처리

fetch 메서드의 응답 타입이 명확하지 않기 때문에 TypeScript의 타입 체크 기능을 활용하여 응답 타입을 명시적으로 정의할 수 있습니다.

 1// Define the type for the response data
 2interface Post {
 3    userId: number;
 4    id: number;
 5    title: string;
 6    body: string;
 7}
 8
 9const url = 'https://jsonplaceholder.typicode.com/posts';
10
11fetch(url)
12    .then(response => response.json())
13    .then((data: Post[]) => {
14        data.forEach(post => {
15            console.log(`Title: ${post.title}`);
16        });
17    })
18    .catch(error => {
19        console.error('Error fetching data:', error);
20    });
  • fetch로 가져온 데이터에 Post 타입을 적용하여 타입 안전하게 응답을 처리하고, 각 게시글의 제목을 콘솔에 출력하는 코드입니다.

POST 요청의 예제

서버에 데이터를 보낼 때는 POST 메서드를 사용하세요. 본문에 JSON 데이터를 보낼 때는 headersbody를 지정하세요.

 1const postData = {
 2    title: 'foo',
 3    body: 'bar',
 4    userId: 1
 5};
 6
 7fetch('https://jsonplaceholder.typicode.com/posts', {
 8        method: 'POST',
 9        headers: {
10            'Content-Type': 'application/json'
11        },
12        body: JSON.stringify(postData)
13    })
14    .then(response => response.json())
15    .then(data => {
16        console.log('Created post:', data);
17    })
18    .catch(error => {
19        console.error('Error posting data:', error);
20    });
  • 이 코드는 JSON 형식으로 데이터를 서버에 POST 요청으로 보내고, 응답을 JSON으로 받아 콘솔에 출력합니다.

비동기 함수(async/await)를 사용한 Fetch

TypeScript에서 async/await를 사용하면 비동기 처리를 더 간단하게 작성할 수 있습니다.

 1// Define the type for the response data
 2interface Post {
 3    userId: number;
 4    id: number;
 5    title: string;
 6    body: string;
 7}
 8
 9async function fetchPosts() {
10    try {
11        const response = await fetch('https://jsonplaceholder.typicode.com/posts');
12        if (!response.ok) {
13            throw new Error('Network response was not ok');
14        }
15        const data: Post[] = await response.json();
16        console.log(data);
17    } catch (error) {
18        console.error('Fetch error:', error);
19    }
20}
21
22fetchPosts();
  • async/await 문법을 사용하여 게시글 데이터를 비동기적으로 가져오고, 응답을 Post[] 타입으로 처리하여 콘솔에 출력합니다.

XMLHttpRequest

XMLHttpRequest는 기존의 API로, Fetch API에 비해 다소 복잡하지만 브라우저 호환성이나 고급 제어가 필요한 경우 사용할 수 있습니다.

XMLHttpRequest의 기본 사용법

아래는 GET 요청을 사용하는 예제입니다.

 1const xhr = new XMLHttpRequest();
 2xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
 3
 4xhr.onreadystatechange = function () {
 5    if (xhr.readyState === 4 && xhr.status === 200) {
 6        const data = JSON.parse(xhr.responseText);
 7        console.log(data);
 8    }
 9};
10
11xhr.send();
  • XMLHttpRequest를 사용해 지정된 URL로 GET 요청을 보내고, 응답을 JSON으로 파싱하여 콘솔에 출력합니다.

POST 요청의 예제

서버에 데이터를 보낼 때는 open 메서드에서 POST를 지정하고 send를 사용하여 데이터를 보내세요.

 1const xhr = new XMLHttpRequest();
 2xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts', true);
 3xhr.setRequestHeader('Content-Type', 'application/json');
 4
 5const postData = JSON.stringify({
 6    title: 'foo',
 7    body: 'bar',
 8    userId: 1
 9});
10
11xhr.onreadystatechange = function () {
12    if (xhr.readyState === 4 && xhr.status === 201) {
13        console.log('Created post:', xhr.responseText);
14    }
15};
16
17xhr.send(postData);
  • XMLHttpRequest를 사용해 JSON 형식의 데이터를 서버에 POST 요청으로 보내고, 생성된 데이터를 포함한 응답을 콘솔에 출력합니다.

XMLHttpRequest에서 에러 처리

onerror 이벤트를 사용하여 요청 에러를 처리할 수 있습니다.

 1const xhr = new XMLHttpRequest();
 2xhr.open('GET', 'https://jsonplaceholder.typicode.com/posts', true);
 3
 4xhr.onerror = function () {
 5    console.error('Request failed');
 6};
 7
 8xhr.onload = function () {
 9    if (xhr.status === 200) {
10        console.log('Response:', xhr.responseText);
11    } else {
12        console.error('Error:', xhr.status);
13    }
14};
15
16xhr.send();
  • XMLHttpRequestGET 요청을 실행하고, onerror로 요청 오류를 처리하여 성공과 실패 모두에 대해 적절히 응답을 로그합니다.

Fetch API와 XMLHttpRequest의 비교

기능 Fetch API XMLHttpRequest
현대적인 API ×
Promise 지원 ×
가독성 높음 (async/await와 잘 작동함) 낮음 (많은 콜백)
브라우저 호환성 일부 오래된 브라우저에서는 지원되지 않음 모든 주요 브라우저에서 지원됨
진행 상황 추적 △ (ReadableStream으로 가능) ○ (onprogress 이벤트 사용 가능)
에러 처리 Promise 체인에서 에러를 잡을 수 있음 onerror 사용 필요

요약

TypeScript에서는 Fetch API를 사용하여 간결하고 타입 안전한 비동기 요청 코드를 작성할 수 있습니다. 한편, XMLHttpRequest는 오래된 API이지만 특정 상황에서는 여전히 사용될 수 있습니다. 일반적으로 간단하고 현대적인 Fetch API를 사용하는 것이 권장되지만, 브라우저 호환성이나 진행 상태 추적이 필요하다면 XMLHttpRequest도 고려할 수 있습니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video