在 Vue 中處理 404 錯誤組件(component)設計:新手指南
更新日期: 2025 年 1 月 1 日
本文為 Django + Vue 前後端分離解析,第 24 篇:
- 前後端分離的 404 錯誤處理:步驟指南
- 正常網頁與 API 接口:新手指南
- GraphQL 與 REST:理解新時代的 API 設計
- 為什麼自定義 404 頁面需要同時支持 API 和 HTML:新手指南
- 前後端分離中的路由與錯誤處理:新手指南
- 設計後端 API 的 404 錯誤處理:新手指南
- 前端與後端的 HTTP 請求與響應協議
- Django 中自定義 404 專案架構的最佳實踐
- 深入理解 Django 中的自定義 404 views 函數處理解析
- Django 的 handler404:自定義 404 錯誤頁面的核心
- Django 的 render 函數與 status 參數:為什麼重要?
- 使用 Accept 判斷請求格式:如何實現靈活的錯誤處理?
- 使用 Esbuild 搭建 Vue 開發環境的指南
- 新手入門:TailwindCSS 與 DaisyUI 的整合指南
- Django 靜態文件管理:static 與 staticfiles 完整指南
- 使用 WhiteNoise 簡化 Django 靜態文件管理:新手入門指南
- Vue 與 Django 整合:從編輯到部署的完整指南
- Django 與 Vue 的專案目錄與設計流程指南
- Django + Vue 前後端分離架構:後端路由渲染解析
- Vue 3 應用的主入口詳解:如何初始化應用
- 探索 Vue 應用的根組件:App.vue 的角色與設計
- Vue.js 單頁應用(SPA)邏輯與運作流程詳解
- 新手指南:使用 Axios 實現高效的 HTTP 請求
- 在 Vue 中處理 404 錯誤組件(component)設計:新手指南 👈 所在位置
- Vue Router 新手指南:設置 404 錯誤頁面
在使用 Vue 開發前後端分離的應用時,前端需要從後端 API 獲取數據並渲染頁面。
然而,API 請求可能會因錯誤的路徑或資源不存在返回 404 錯誤。
本指南將介紹如何使用 Vue 的 Composition API 和 Axios,捕獲並處理這些錯誤響應,並將錯誤信息動態顯示在頁面上。
問題描述
後端 API 返回的 JSON 格式如下:
def api_not_found(request):
return JsonResponse({
"error": "Not found",
"status_code": 404,
"detail": "The requested resource was not found",
}, status=404)
響應中包含:
error
:錯誤描述。status_code
:HTTP 狀態碼(404)。detail
:更詳細的錯誤信息。
前端需要根據返回的錯誤數據,動態顯示錯誤信息。
完整範例:404 錯誤頁面組件
以下是一個 Vue 組件範例,處理後端返回的 404 錯誤信息並渲染頁面。
NotFoundPage.vue
<template>
<div>
<h1 v-if="errorMessage">Error {{ errorMessage }}</h1>
<p v-if="errorDetail">{{ errorDetail }}</p>
<router-link to="/">Go Back Home</router-link>
</div>
</template>
<script>
import { ref, onMounted } from "vue";
import axios from "axios";
export default {
name: "NotFoundPage",
setup() {
const errorMessage = ref("");
const errorDetail = ref("");
onMounted(async () => {
try {
const response = await axios.get("/api/404/", {
headers: { Accept: "application/json" },
});
// 通常不會執行這段代碼,因為 API 返回 404 錯誤
errorMessage.value = response.data.status_code || "Error not specified.";
errorDetail.value = response.data.detail || "No additional details provided.";
} catch (error) {
console.error("Error fetching JSON data:", error.response || error.message);
if (error.response) {
// 從伺服器的錯誤響應中提取數據
errorMessage.value = error.response.data.status_code || "Error not specified.";
errorDetail.value = error.response.data.detail || "No additional details provided.";
} else {
// 處理伺服器無響應或其他網絡錯誤
errorMessage.value = "An unexpected error occurred.";
errorDetail.value = "No additional details available.";
}
}
});
return { errorMessage, errorDetail };
},
};
</script>
<style scoped>
/* 添加樣式以美化錯誤頁面 */
h1 {
color: red;
font-size: 2rem;
}
p {
color: gray;
}
</style>
代碼詳細解析
Template 部分
<template>
<div>
<h1 v-if="errorMessage">Error {{ errorMessage }}</h1>
<p v-if="errorDetail">{{ errorDetail }}</p>
<router-link to="/">Go Back Home</router-link>
</div>
</template>
功能說明
- 條件渲染:
- 當
errorMessage
和errorDetail
有值時,動態顯示錯誤信息。
- 當
- 導航鏈接:
- 使用 Vue Router 的
<router-link>
提供返回首頁的導航。
- 使用 Vue Router 的
Script 部分
Composition API 的應用
import { ref, onMounted } from "vue";
import axios from "axios";
export default {
name: "NotFoundPage",
setup() {
const errorMessage = ref("");
const errorDetail = ref("");
onMounted(async () => {
try {
const response = await axios.get("/api/404/", {
headers: { Accept: "application/json" },
});
errorMessage.value = response.data.status_code || "Error not specified.";
errorDetail.value = response.data.detail || "No additional details provided.";
} catch (error) {
console.error("Error fetching JSON data:", error.response || error.message);
if (error.response) {
// 提取錯誤響應中的數據
errorMessage.value = error.response.data.status_code || "Error not specified.";
errorDetail.value = error.response.data.detail || "No additional details provided.";
} else {
errorMessage.value = "An unexpected error occurred.";
errorDetail.value = "No additional details available.";
}
}
});
return { errorMessage, errorDetail };
},
};
關鍵邏輯
- 響應式數據
- 使用
ref
定義errorMessage
和errorDetail
,確保數據更新時模板自動重新渲染。 - 初始值設為空字符串。
- 使用
- 發送 HTTP 請求
const response = await axios.get("/api/404/", {
headers: { Accept: "application/json" },
});
- 發送帶有
Accept: application/json
的請求,告知後端返回 JSON 格式數據。 - 由於 API 返回 404,
catch
會捕獲到錯誤。
- 處理錯誤響應
if (error.response) {
errorMessage.value = error.response.data.status_code || "Error not specified.";
errorDetail.value = error.response.data.detail || "No additional details provided.";
}
- 使用
error.response
提取後端返回的status_code
和detail
。 - 如果後端無返回,設置默認錯誤信息。
- 處理其他錯誤
if (error.response) {
errorMessage.value = error.response.data.status_code || "Error not specified.";
errorDetail.value = error.response.data.detail || "No additional details provided.";
}
- 針對網絡錯誤或伺服器無響應的情況,提供通用的錯誤提示。
Style 部分
<style scoped>
h1 {
color: red;
font-size: 2rem;
}
p {
color: gray;
}
</style>
功能說明
- 使用
scoped
修飾符確保樣式僅作用於當前組件。 - 添加基本樣式,突出錯誤信息。
執行流程總結
- 組件初始化
- Vue 執行
setup
函數,定義響應式數據。
- Vue 執行
- 組件掛載
- 在
onMounted
鉤子中發送 API 請求。
- 在
- 處理響應
- 提取錯誤響應中的數據,更新
errorMessage
和errorDetail
。 - 網絡錯誤則設置通用錯誤消息。
- 提取錯誤響應中的數據,更新
- 渲染頁面
- 根據更新後的數據,動態顯示錯誤信息。
結語
這篇指南展示了如何在 Vue 中設置 HTTP Header 並處理 404 錯誤響應。
通過 Vue 的 Composition API 和 Axios,我們可以輕鬆實現數據的動態綁定和錯誤處理,為用戶提供良好的交互體驗。
希望本指南能幫助您更好地應對類似場景!