You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
// utils/apiClient.ts
|
|
|
|
|
import { useAuthStore } from '~/stores/user';
|
|
|
|
|
import { ofetch } from 'ofetch';
|
|
|
|
|
|
|
|
|
|
export function apiClient<T>(url: string, options: any = {}): Promise<T> {
|
|
|
|
|
const config = useRuntimeConfig();
|
|
|
|
|
const baseURL = config.public.apiBaseUrl;
|
|
|
|
|
const authStore = useAuthStore();
|
|
|
|
|
|
|
|
|
|
const headers: Record<string, string> = {
|
|
|
|
|
'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<T>(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;
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
}
|