IntelliClass_FE/utils/http.ts
Timothy Yin b05f954923
feat: add authentication requirements to course preparation and resources pages
fix: update home page background image and remove unnecessary redirect code

chore: update pnpm lock file with new dependencies for auto-animate and svg spinners

delete: remove unused images from public directory

refactor: modify course and user types for better clarity and structure

feat: implement course API with CRUD operations and teacher team management

feat: create user authentication page with login functionality and validation

feat: add login state management with Pinia for user session handling

style: create reusable UI components for cards and tabs

chore: implement HTTP utility for API requests with error handling
2025-04-06 00:25:20 +08:00

40 lines
911 B
TypeScript

import type { NitroFetchOptions, NitroFetchRequest } from "nitropack";
import { FetchError } from "ofetch";
/**
* 封装 HTTP 请求
* @param url 请求的路径
* @param options 请求选项
* @returns 返回请求结果
*
* @throws {FetchError} 请求失败时抛出错误
*/
export const http = async <T>(
url: string,
options?: NitroFetchOptions<NitroFetchRequest>
) => {
const loginState = useLoginState();
const runtimeConfig = useRuntimeConfig();
const baseURL = runtimeConfig.public.baseURL as string;
try {
const data = await $fetch<T>(url, {
baseURL,
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${loginState.token}`,
},
...options,
});
return data;
} catch (err: unknown) {
if (err instanceof FetchError) {
throw err;
} else {
throw new FetchError("请求失败");
}
}
};