在 TypeScript 中的 Fetch/XMLHttpRequest
本文介紹了在 TypeScript 中的 Fetch/XMLHttpRequest。
您可以學習如何使用 Fetch API 和 XMLHttpRequest,以及它們之間的差異。
YouTube Video
在 TypeScript 中的 Fetch/XMLHttpRequest
在 TypeScript 中,HTTP 請求主要使用兩個 API:Fetch API 和 XMLHttpRequest。通過使用 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 });- 此程式碼將
Post類型套用到透過fetch取得的資料,並以型別安全的方式處理回應,最後將每篇貼文的標題輸出到主控台。
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以POST請求將 JSON 格式資料送至伺服器,並將包含已建立資料的回應輸出到主控台。
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 頻道。