forked from 77media/video-flow
123 lines
2.6 KiB
TypeScript
123 lines
2.6 KiB
TypeScript
import { getToken, clearAuthData } from './auth';
|
||
|
||
// API基础URL
|
||
const API_BASE_URL = 'https://77.api.qikongjian.com';
|
||
|
||
/**
|
||
* 统一的API请求方法
|
||
*/
|
||
export const apiRequest = async (
|
||
endpoint: string,
|
||
options: RequestInit = {}
|
||
): Promise<any> => {
|
||
const token = getToken();
|
||
|
||
// 构建请求头
|
||
const headers: HeadersInit = {
|
||
'Accept': 'application/json',
|
||
'Content-Type': 'application/json',
|
||
...options.headers,
|
||
};
|
||
|
||
// 添加token到请求头(如果存在)
|
||
if (token) {
|
||
headers['X-EASE-ADMIN-TOKEN'] = token;
|
||
}
|
||
|
||
try {
|
||
const response = await fetch(`${API_BASE_URL}${endpoint}`, {
|
||
...options,
|
||
headers,
|
||
});
|
||
|
||
// 检查响应状态
|
||
if (!response.ok) {
|
||
if (response.status === 401) {
|
||
// Token过期或无效
|
||
clearAuthData();
|
||
window.location.href = '/login';
|
||
throw new Error('身份验证失败,请重新登录');
|
||
}
|
||
throw new Error(`请求失败: ${response.status}`);
|
||
}
|
||
|
||
const data = await response.json();
|
||
|
||
// 检查业务状态码
|
||
if (data.code === '401' || data.status === 401) {
|
||
clearAuthData();
|
||
window.location.href = '/login';
|
||
throw new Error('身份验证失败,请重新登录');
|
||
}
|
||
|
||
return data;
|
||
} catch (error) {
|
||
console.error('API request failed:', error);
|
||
throw error;
|
||
}
|
||
};
|
||
|
||
/**
|
||
* GET请求
|
||
*/
|
||
export const apiGet = (endpoint: string, options: RequestInit = {}) => {
|
||
return apiRequest(endpoint, {
|
||
...options,
|
||
method: 'GET',
|
||
});
|
||
};
|
||
|
||
/**
|
||
* POST请求
|
||
*/
|
||
export const apiPost = (endpoint: string, data?: any, options: RequestInit = {}) => {
|
||
return apiRequest(endpoint, {
|
||
...options,
|
||
method: 'POST',
|
||
body: data ? JSON.stringify(data) : undefined,
|
||
});
|
||
};
|
||
|
||
/**
|
||
* PUT请求
|
||
*/
|
||
export const apiPut = (endpoint: string, data?: any, options: RequestInit = {}) => {
|
||
return apiRequest(endpoint, {
|
||
...options,
|
||
method: 'PUT',
|
||
body: data ? JSON.stringify(data) : undefined,
|
||
});
|
||
};
|
||
|
||
/**
|
||
* DELETE请求
|
||
*/
|
||
export const apiDelete = (endpoint: string, options: RequestInit = {}) => {
|
||
return apiRequest(endpoint, {
|
||
...options,
|
||
method: 'DELETE',
|
||
});
|
||
};
|
||
|
||
/**
|
||
* 文件上传请求
|
||
*/
|
||
export const apiUpload = (endpoint: string, formData: FormData, options: RequestInit = {}) => {
|
||
const token = getToken();
|
||
|
||
const headers: HeadersInit = {
|
||
...options.headers,
|
||
};
|
||
|
||
// 添加token到请求头(如果存在)
|
||
if (token) {
|
||
headers['X-EASE-ADMIN-TOKEN'] = token;
|
||
}
|
||
|
||
return apiRequest(endpoint, {
|
||
...options,
|
||
method: 'POST',
|
||
headers,
|
||
body: formData,
|
||
});
|
||
};
|