Files
cunkebao_v3/SuperAdmin/lib/api-utils.ts
Manus AI 5517457929 sync: 以本地为准同步全量变更至 GitHub
含四端需求文档、前端/后端/超管/触客宝迭代及部署脚本更新;未拉取远程。

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-30 04:24:56 +08:00

67 lines
1.6 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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;
}
}