TypeScriptにおけるFetch/XMLHttpRequest
この記事ではTypeScriptにおけるFetch/XMLHttpRequestについて説明します。
Fetch APIとXMLHttpRequestの使い方や違いについて学べます。
YouTube Video
TypeScriptにおけるFetch/XMLHttpRequest
TypeScriptにおけるHTTPリクエストは、主にFetch APIとXMLHttpRequestの2つを利用して行われます。TypeScriptを使うことで、これらのAPIで非同期通信を行う際に、リクエストやレスポンスの型チェックを導入でき、より安全なコードを書くことができます。以下では、それぞれの使い方を紹介します。
Fetch API
Fetch APIは、PromiseベースのAPIであり、シンプルに非同期通信(HTTPリクエスト)を行うために使われます。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を送信するためには、headersとbodyを指定します。
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 });- このコードは、
POSTリクエストでJSON形式のデータをサーバーに送信し、そのレスポンスを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();- このコードは、
XMLHttpRequestでGETリクエストを実行し、onerrorでリクエストエラーを処理しつつ、成功時や失敗時のレスポンスを適切にログ出力します。
Fetch API と XMLHttpRequest の比較
| 特徴 | Fetch API | XMLHttpRequest |
|---|---|---|
| モダンなAPI | ○ | × |
| Promiseサポート | ○ | × |
| 可読性 | 高い(async/awaitと相性が良い) |
低い(コールバックが多くなる) |
| ブラウザ互換性 | 一部の古いブラウザではサポートされていない | すべての主要ブラウザでサポート |
| 進捗状況の取得 | △(ReadableStreamを使って可能) |
○(onprogressイベントが使える) |
| エラーハンドリング | エラーはPromiseチェーンでキャッチ | onerrorを使う必要がある |
まとめ
TypeScriptでは、Fetch APIを使うことで、非同期リクエストを簡潔に記述し、型安全なコードを書けます。一方、XMLHttpRequestは古いAPIですが、特定の状況下ではまだ使用されることがあります。基本的には、シンプルでモダンなFetch APIを利用することが推奨されますが、ブラウザ互換性や進捗状況の取得が必要な場合には、XMLHttpRequestも検討できます。
YouTubeチャンネルでは、Visual Studio Codeを用いて上記の記事を見ながら確認できます。 ぜひYouTubeチャンネルもご覧ください。