import type { AsyncData, UseFetchOptions } from '#app' export function requestCore(url: string, options: UseFetchOptions) { // const config = useRuntimeConfig() return useFetch(url, { baseURL: "https://cantyonion.site", retry: false, onRequest({ options }) { let token: string = "" if (import.meta.client) { token = localStorage.getItem("token") || "" } if (!options.headers.get('Authorization')) options.headers.set('Authorization', `Bearer ${token}`) }, onResponse({ response }) { // HTTP状态码2XX/3XX执行,否则不执行 if (response.status < 200 || response.status >= 400) { console.error(`HTTP 错误: ${response.status}`) return } // 业务code状态码判断 // if (response._data.code !== 200) { // // } }, onResponseError({ response }) { emitter.emit('eventBus', { level: 'error', title: `HTTP错误:${response.status}`, message: response.statusText }) }, ...options }) } export function get(url: string, options?: UseFetchOptions): () => Promise { let result: AsyncData | null = null return async (): Promise => { if (result != null) { await result.refresh() return result.data.value } result = await requestCore(url, { method: 'GET', ...options, }) as AsyncData return result.data.value } }