// utils/apiClient.ts import { useAuthStore } from '~/stores/user'; import { ofetch } from 'ofetch'; export function apiClient(url: string, options: any = {}): Promise { const config = useRuntimeConfig(); const baseURL = config.public.apiBaseUrl; const authStore = useAuthStore(); const headers: Record = { 'Content-Type': 'application/json', ...options.headers }; console.log("授权:", authStore.token, options.headers); // 添加授权头 if (authStore.token) { headers['Authorization'] = `Bearer ${authStore.token}`; } console.log("请求头部信息:", headers); return ofetch(url, { baseURL, ...options, headers, async onResponseError({ response }) { // 处理401未授权错误 if (response.status === 401) { try { // TODO 尝试刷新令牌 // const newToken = await authStore.refreshToken(); // const newToken = ''; // 更新请求头 // headers['Authorization'] = `Bearer ${newToken}`; // console.log("重新授权"); // 使用新的token重试原始请求 const retryOptions = { ...options, headers: { ...options.headers, Authorization: `Bearer ${authStore.token}` } }; return ofetch(url, { baseURL, ...retryOptions }); } catch (refreshError) { // 刷新失败,执行登出 await authStore.logout(); navigateTo('/login'); throw new Error('Session expired, please login again'); } } throw response; } }); }