67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
import { getConfig } from './config';
|
||
import { clearAdminInfo } from './utils';
|
||
|
||
/**
|
||
* API响应接口
|
||
*/
|
||
export interface ApiResponse<T = any> {
|
||
code: number;
|
||
msg: string;
|
||
data?: T;
|
||
}
|
||
|
||
/**
|
||
* API请求函数
|
||
* @param endpoint API端点
|
||
* @param method HTTP方法
|
||
* @param body 请求数据
|
||
* @param headers 请求头
|
||
* @returns API响应
|
||
*/
|
||
export async function apiRequest(
|
||
endpoint: string,
|
||
method: string = 'GET',
|
||
body?: any,
|
||
headers: HeadersInit = {}
|
||
): Promise<ApiResponse> {
|
||
const { apiBaseUrl } = getConfig();
|
||
const url = `${apiBaseUrl}${endpoint}`;
|
||
|
||
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
|
||
|
||
const defaultHeaders: Record<string, string> = {
|
||
'Content-Type': 'application/json',
|
||
'Accept': 'application/json',
|
||
...(headers as Record<string, string>),
|
||
};
|
||
|
||
if (token) {
|
||
defaultHeaders.Authorization = `Bearer ${token}`;
|
||
}
|
||
|
||
const options: RequestInit = {
|
||
method,
|
||
headers: defaultHeaders,
|
||
...(body && { body: JSON.stringify(body) })
|
||
};
|
||
|
||
try {
|
||
const response = await fetch(url, options);
|
||
const data = await response.json();
|
||
|
||
// 如果接口返回的code不是200,抛出错误
|
||
if (data && data.code !== 200) {
|
||
// 认证失效:清 token 并跳转登录,避免各页表格只显示「授权已过期或无效」
|
||
if (data.code === 401 && typeof window !== 'undefined') {
|
||
clearAdminInfo();
|
||
window.location.href = '/login';
|
||
}
|
||
throw data; // 抛出响应结果作为错误
|
||
}
|
||
|
||
return data;
|
||
} catch (error) {
|
||
console.error('API请求失败:', error);
|
||
throw error;
|
||
}
|
||
}
|