Files
cunkebao_v3/SuperAdmin/lib/api-utils.ts

80 lines
2.4 KiB
TypeScript
Raw Normal View History

2025-04-10 11:54:21 +08:00
import { getConfig } from './config';
/**
2025-04-10 17:49:42 +08:00
* API响应接口
2025-04-10 11:54:21 +08:00
*/
interface ApiResponse {
2025-04-10 11:54:21 +08:00
code: number;
msg: string;
data?: any;
2025-04-10 11:54:21 +08:00
}
/**
2025-04-10 17:49:42 +08:00
* API请求函数
2025-04-10 11:54:21 +08:00
* @param endpoint API端点
* @param method HTTP方法
* @param body
* @param headers
2025-04-10 11:54:21 +08:00
* @returns API响应
*/
export async function apiRequest(
2025-04-10 11:54:21 +08:00
endpoint: string,
method: string = 'GET',
body?: any,
headers: HeadersInit = {}
): Promise<ApiResponse> {
const url = `${process.env.NEXT_PUBLIC_API_BASE_URL}${endpoint}`;
2025-04-10 11:54:21 +08:00
// 从localStorage获取token和admin_id
const token = typeof window !== 'undefined' ? localStorage.getItem('admin_token') : null;
const adminId = typeof window !== 'undefined' ? localStorage.getItem('admin_id') : null;
2025-04-10 11:54:21 +08:00
// 设置cookie
if (typeof window !== 'undefined' && token && adminId) {
const domain = new URL(process.env.NEXT_PUBLIC_API_BASE_URL || '').hostname;
document.cookie = `admin_token=${token}; path=/; domain=${domain}`;
document.cookie = `admin_id=${adminId}; path=/; domain=${domain}`;
2025-04-10 11:54:21 +08:00
}
const defaultHeaders = {
'Content-Type': 'application/json',
'Accept': 'application/json',
...headers
};
2025-04-10 17:49:42 +08:00
const options: RequestInit = {
2025-04-10 11:54:21 +08:00
method,
headers: defaultHeaders,
credentials: 'include', // 允许跨域请求携带cookies
mode: 'cors', // 明确指定使用CORS模式
...(body && { body: JSON.stringify(body) })
2025-04-10 11:54:21 +08:00
};
2025-04-10 11:54:21 +08:00
try {
2025-04-10 17:49:42 +08:00
const response = await fetch(url, options);
const data = await response.json();
2025-04-10 11:54:21 +08:00
// 如果接口返回的code不是200抛出错误
if (data && data.code !== 200) {
2025-04-10 17:49:42 +08:00
// 如果是认证错误,清除登录信息
if (data.code === 401) {
2025-04-10 17:49:42 +08:00
if (typeof window !== 'undefined') {
localStorage.removeItem('admin_id');
localStorage.removeItem('admin_name');
localStorage.removeItem('admin_account');
localStorage.removeItem('admin_token');
// 清除cookie
const domain = new URL(process.env.NEXT_PUBLIC_API_BASE_URL || '').hostname;
document.cookie = 'admin_token=; path=/; domain=' + domain + '; expires=Thu, 01 Jan 1970 00:00:00 GMT';
document.cookie = 'admin_id=; path=/; domain=' + domain + '; expires=Thu, 01 Jan 1970 00:00:00 GMT';
2025-04-10 17:49:42 +08:00
}
2025-04-10 11:54:21 +08:00
}
throw data; // 抛出响应结果作为错误
2025-04-10 11:54:21 +08:00
}
return data;
2025-04-10 11:54:21 +08:00
} catch (error) {
console.error('API请求失败:', error);
2025-04-10 17:49:42 +08:00
throw error;
2025-04-10 11:54:21 +08:00
}
}