diff --git a/frontend/post.html b/frontend/post.html index e5353db..a277c70 100644 --- a/frontend/post.html +++ b/frontend/post.html @@ -113,9 +113,24 @@ const user = localStorage.getItem('user'); if (token && user) { - currentUser = JSON.parse(user); - document.getElementById('replyForm').classList.remove('hidden'); - document.getElementById('loginHint').classList.add('hidden'); + // 验证 token 是否有效 + try { + const res = await fetch('/api/user', { + headers: { 'Authorization': 'Bearer ' + token } + }); + if (res.ok) { + currentUser = JSON.parse(user); + document.getElementById('replyForm').classList.remove('hidden'); + document.getElementById('loginHint').classList.add('hidden'); + } else { + // token 无效,清除 + localStorage.removeItem('token'); + localStorage.removeItem('user'); + currentUser = null; + } + } catch (e) { + console.error('验证登录失败', e); + } } } @@ -274,6 +289,11 @@ } async function saveEdit() { + if (!currentUser) { + alert('请先登录'); + return; + } + const title = document.getElementById('editTitle').value.trim(); const content = document.getElementById('editContent').value.trim(); const tagsStr = document.getElementById('editTags').value.trim(); @@ -288,11 +308,18 @@ return; } + const token = localStorage.getItem('token'); + if (!token) { + alert('登录已过期,请重新登录'); + window.location.href = '/login'; + return; + } + try { const res = await fetch('/api/posts/' + currentPostId + '/edit', { method: 'POST', headers: { - 'Authorization': 'Bearer ' + localStorage.getItem('token'), + 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify({ title, content, tags }) @@ -324,11 +351,18 @@ return; } + const token = localStorage.getItem('token'); + if (!token) { + alert('登录已过期,请重新登录'); + window.location.href = '/login'; + return; + } + try { const res = await fetch('/api/posts/' + currentPostId + '/reply', { method: 'POST', headers: { - 'Authorization': 'Bearer ' + localStorage.getItem('token'), + 'Authorization': 'Bearer ' + token, 'Content-Type': 'application/json' }, body: JSON.stringify({ content }) @@ -352,11 +386,18 @@ return; } + const token = localStorage.getItem('token'); + if (!token) { + alert('登录已过期,请重新登录'); + window.location.href = '/login'; + return; + } + try { const res = await fetch('/api/posts/' + currentPostId + '/like', { method: 'POST', headers: { - 'Authorization': 'Bearer ' + localStorage.getItem('token') + 'Authorization': 'Bearer ' + token } }); const data = await res.json();