在 API 資料還沒載入完成前,通常會顯示「載入中...」或 loading 動畫。
API 請求可能失敗,原因可能是:
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>
fetch
網址改成錯的,觀察錯誤訊息是否正確顯示。fetchPosts()
。