|
|
@@ -1,4 +1,5 @@
|
|
|
-import { getStorage } from '@/utils/storage'
|
|
|
+import { getStorage, removeStorage } from '@/utils/storage'
|
|
|
+import router from '@/router'
|
|
|
|
|
|
|
|
|
export interface ApiResponse<T = any> {
|
|
|
@@ -8,7 +9,6 @@ export interface ApiResponse<T = any> {
|
|
|
}
|
|
|
|
|
|
function showError(msg: string): Promise<void> {
|
|
|
- // 不使用 Vant showToast(在非组件上下文中不可靠),直接用 DOM 插入
|
|
|
const el = document.createElement('div')
|
|
|
el.textContent = msg
|
|
|
el.style.cssText =
|
|
|
@@ -21,6 +21,13 @@ function showError(msg: string): Promise<void> {
|
|
|
return new Promise((resolve) => setTimeout(resolve, 150))
|
|
|
}
|
|
|
|
|
|
+function handleUnauthorized() {
|
|
|
+ removeStorage('token')
|
|
|
+ showError('登录已过期,请重新登录').then(() => {
|
|
|
+ router.push('/login')
|
|
|
+ })
|
|
|
+}
|
|
|
+
|
|
|
export async function request<T = any>(url: string, options?: RequestInit): Promise<ApiResponse<T>> {
|
|
|
|
|
|
const token = getStorage('token')
|
|
|
@@ -41,6 +48,13 @@ export async function request<T = any>(url: string, options?: RequestInit): Prom
|
|
|
await showError('网络连接失败,请检查网络')
|
|
|
throw new Error('网络连接失败')
|
|
|
}
|
|
|
+
|
|
|
+ // 401 未授权:清除 token 并跳转登录页
|
|
|
+ if (res.status === 401) {
|
|
|
+ handleUnauthorized()
|
|
|
+ throw new Error('未授权')
|
|
|
+ }
|
|
|
+
|
|
|
// HTTP 状态码错误(500、404 等)
|
|
|
if (!res.ok) {
|
|
|
let errMsg = ''
|
|
|
@@ -68,7 +82,6 @@ export async function request<T = any>(url: string, options?: RequestInit): Prom
|
|
|
|
|
|
if (json.code !== 200) {
|
|
|
const errMsg = json.msg || '请求失败'
|
|
|
- // await showError(errMsg)
|
|
|
throw new Error(errMsg)
|
|
|
}
|
|
|
return json
|