fix: 管理后台登录态过期不再停留空数据页——任何接口401自动清token弹登录框

This commit is contained in:
Hermes Agent
2026-09-22 21:44:52 +08:00
parent df8dd3d3dc
commit 8b9ff56360
2 changed files with 18 additions and 2 deletions
+5 -1
View File
@@ -27,7 +27,7 @@
</template>
<script setup>
import { onMounted, ref, provide } from 'vue'
import { onMounted, ref, provide, onBeforeUnmount } from 'vue'
import { getToken, setToken, clearToken, apiPost } from './api'
import Dashboard from './views/Dashboard.vue'
import Users from './views/Users.vue'
@@ -43,6 +43,10 @@ const token = ref(getToken())
const view = ref('dashboard')
// 子页面跳转菜单(如看板→访问日志)
const goto = (key) => { view.value = key }
// 登录态过期:任何接口401 → 回登录框
const onAuthExpired = () => { token.value = '' }
onMounted(() => window.addEventListener('admin-auth-expired', onAuthExpired))
onBeforeUnmount(() => window.removeEventListener('admin-auth-expired', onAuthExpired))
provide('goto', goto)
const username = ref(''), password = ref(''), busy = ref(false), error = ref('')
+13 -1
View File
@@ -5,7 +5,14 @@ export function clearToken() { localStorage.removeItem(TOKEN_KEY) }
export function apiGet(path) {
return fetch(path, { headers: { Authorization: `Bearer ${getToken()}` } })
.then(r => r.json())
.then(r => {
if (r.status === 401) {
clearToken()
window.dispatchEvent(new CustomEvent('admin-auth-expired'))
throw new Error('登录已过期')
}
return r.json()
})
.then(j => j.data !== undefined ? j.data : j)
.catch(e => { throw new Error(e.message) })
}
@@ -14,6 +21,11 @@ export function apiGet(path) {
function handleResponse(r) {
return r.json().then(j => {
if (!r.ok) {
// 401=登录态过期:清token并通知全局弹登录框(否则面板停留空数据)
if (r.status === 401) {
clearToken()
window.dispatchEvent(new CustomEvent('admin-auth-expired'))
}
throw new Error(j.error || j.message || `请求失败(${r.status})`)
}
return j