fix: 编辑帖子时验证token有效性
- checkLogin时调用API验证token - saveEdit/submitReply/likePost函数增加token检查 - token过期时自动跳转登录页
This commit is contained in:
@@ -113,9 +113,24 @@
|
||||
const user = localStorage.getItem('user');
|
||||
|
||||
if (token && user) {
|
||||
// 验证 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();
|
||||
|
||||
Reference in New Issue
Block a user