iT邦幫忙

2025 iThome 鐵人賽

DAY 13
0
Modern Web

Modern Web:從基礎、框架到前端學習系列 第 19

Day19:API 資料渲染與錯誤處理

  • 分享至 

  • xImage
  •  

學習目標

  1. 了解如何在UI 上顯示 Loading 狀態
  2. 學會用try/catch來處理請求錯誤。
  3. 顯示錯誤訊息給使用者,而不是只停在 console。
  4. 做一個文章清單渲染頁面 (含錯誤處理)

理論講解

1.Loading 狀態處理

在 API 資料還沒載入完成前,通常會顯示「載入中...」或 loading 動畫。

2.錯誤處理

API 請求可能失敗,原因可能是:

  • 網路斷線
  • API 網址錯誤
  • 伺服器錯誤(500)
    👉 必須在 UI 告訴使用者錯誤原因。

3.try/catch 結構

try {
  let response = await fetch("https://example.com/api");
  if (!response.ok) throw new Error("伺服器錯誤:" + response.status);
  let data = await response.json();
} catch (error) {
  console.error("錯誤發生:", error);
}

實作練習:文章清單渲染 + 錯誤處理

檔名:day19_fetch_error.html

<!DOCTYPE html>
<html lang="zh-Hant">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Day19 - API 錯誤處理</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      padding: 20px;
    }
    .post {
      border: 1px solid #ccc;
      border-radius: 8px;
      padding: 12px;
      margin-bottom: 10px;
    }
    .post h3 {
      margin: 0;
      color: darkblue;
    }
    .loading {
      color: gray;
      font-style: italic;
    }
    .error {
      color: red;
      font-weight: bold;
    }
  </style>
</head>
<body>
  <h1>文章清單</h1>
  <div id="status" class="loading">載入中...</div>
  <div id="postList"></div>

  <script>
    const statusDiv = document.getElementById("status");
    const postList = document.getElementById("postList");

    async function fetchPosts() {
      try {
        statusDiv.textContent = "載入中...";
        postList.innerHTML = "";

        // ✅ 故意改錯網址測試錯誤處理
        let response = await fetch("https://jsonplaceholder.typicode.com/posts");

        // 如果伺服器回應不是 200~299,就拋出錯誤
        if (!response.ok) {
          throw new Error("伺服器錯誤:" + response.status);
        }

        let posts = await response.json();

        // 清空狀態訊息
        statusDiv.textContent = "";

        // 渲染文章
        posts.slice(0, 5).forEach(post => {
          const div = document.createElement("div");
          div.className = "post";
          div.innerHTML = `
            <h3>${post.title}</h3>
            <p>${post.body}</p>
          `;
          postList.appendChild(div);
        });
      } catch (error) {
        statusDiv.textContent = "載入失敗:" + error.message;
        statusDiv.className = "error";
      }
    }

    fetchPosts();
  </script>
</body>
</html>

今日作業

  1. 嘗試把fetch網址改成錯的,觀察錯誤訊息是否正確顯示。
  2. 幫頁面加一個「重新整理」按鈕,點擊後重新呼叫fetchPosts()
  3. 挑戰:在錯誤發生時,顯示一個Retry按鈕,點擊後再次嘗試抓資料。

上一篇
Day18:Fetch API 與資料請求
下一篇
Day 20:RESTful API 設計與整合
系列文
Modern Web:從基礎、框架到前端學習20
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言