後端會要求請求者附帶身份憑證(例如JWT Token)。
若沒有或過期,就會回傳401 Unauthorized錯誤。
每次發送 API 請求時,在 HTTP Header 加上:
Authorization: Bearer <你的Token>
專案結構
login-demo/
├── index.html // 登入頁
├── member.html // 會員頁面
├── style.css
├── script.js
└── member.js
index.html
沿用 Day21 的登入頁即可。
member.html
登入成功後可以從 localStorage 讀取 Token,並呼叫一個受保護的 API。
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<title>會員中心</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>會員中心</h1>
<div id="content">
<p class="loading">載入中...</p>
</div>
<button id="logout">登出</button>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="member.js"></script>
</body>
</html>
member.js
const contentDiv = document.getElementById('content');
const logoutBtn = document.getElementById('logout');
// 取得 Token
const token = localStorage.getItem('authToken');
if (!token) {
alert('請先登入!');
window.location.href = 'index.html';
}
// 模擬受保護 API
const API_URL = 'https://reqres.in/api/users/2';
async function fetchMemberData() {
try {
const res = await axios.get(API_URL, {
headers: {
'Authorization': `Bearer ${token}`
}
});
const user = res.data.data;
contentDiv.innerHTML = `
<div class="member-card">
<img src="${user.avatar}" alt="${user.first_name}" />
<h3>${user.first_name} ${user.last_name}</h3>
<p>Email:${user.email}</p>
</div>
`;
} catch (err) {
console.error(err);
if (err.response && err.response.status === 401) {
contentDiv.innerHTML = `<p class="error">Token 無效或已過期,請重新登入。</p>`;
localStorage.removeItem('authToken');
} else {
contentDiv.innerHTML = `<p class="error">載入會員資料失敗。</p>`;
}
}
}
fetchMemberData();
// 登出
logoutBtn.addEventListener('click', () => {
localStorage.removeItem('authToken');
window.location.href = 'index.html';
});
style.css(延伸)
.member-card {
display: flex;
flex-direction: column;
align-items: center;
background: #f9f9f9;
padding: 20px;
border-radius: 12px;
box-shadow: 0 2px 5px rgba(0,0,0,0.1);
margin-top: 20px;
}
.member-card img {
width: 100px;
border-radius: 50%;
margin-bottom: 10px;
}
.loading {
color: gray;
}
.error {
color: red;
font-weight: bold;
}