feat(client): 添加对authToken的处理 & 封装请求头
This commit is contained in:
@@ -1 +1,79 @@
|
||||
export default {};
|
||||
import { getAuthToken } from '../utils/auth';
|
||||
|
||||
interface RequestOptions extends RequestInit {
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* 统一的fetch请求封装
|
||||
* 自动添加Authorization头部
|
||||
*/
|
||||
export const apiRequest = async <T = any>(
|
||||
endpoint: string,
|
||||
options: RequestOptions = {}
|
||||
): Promise<T> => {
|
||||
const authToken = getAuthToken();
|
||||
|
||||
const url = endpoint;
|
||||
|
||||
// 准备请求头
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.headers,
|
||||
};
|
||||
|
||||
// 如果有authToken,添加Authorization头
|
||||
if (authToken) {
|
||||
headers.authorization = `Bearer ${authToken}`;
|
||||
}
|
||||
|
||||
// 发起请求
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
headers,
|
||||
});
|
||||
|
||||
// 处理响应
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`);
|
||||
}
|
||||
|
||||
// 尝试解析JSON,如果失败则返回响应对象
|
||||
try {
|
||||
return await response.json();
|
||||
} catch {
|
||||
return response as any;
|
||||
}
|
||||
};
|
||||
|
||||
// 便捷的HTTP方法封装
|
||||
export const api = {
|
||||
get: <T = any>(endpoint: string, options?: RequestOptions): Promise<T> =>
|
||||
apiRequest<T>(endpoint, { ...options, method: 'GET' }),
|
||||
|
||||
post: <T = any>(endpoint: string, data?: any, options?: RequestOptions): Promise<T> =>
|
||||
apiRequest<T>(endpoint, {
|
||||
...options,
|
||||
method: 'POST',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
}),
|
||||
|
||||
put: <T = any>(endpoint: string, data?: any, options?: RequestOptions): Promise<T> =>
|
||||
apiRequest<T>(endpoint, {
|
||||
...options,
|
||||
method: 'PUT',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
}),
|
||||
|
||||
patch: <T = any>(endpoint: string, data?: any, options?: RequestOptions): Promise<T> =>
|
||||
apiRequest<T>(endpoint, {
|
||||
...options,
|
||||
method: 'PATCH',
|
||||
body: data ? JSON.stringify(data) : undefined,
|
||||
}),
|
||||
|
||||
delete: <T = any>(endpoint: string, options?: RequestOptions): Promise<T> =>
|
||||
apiRequest<T>(endpoint, { ...options, method: 'DELETE' }),
|
||||
};
|
||||
|
||||
export default api;
|
||||
|
||||
Reference in New Issue
Block a user