import type { AsyncData, UseFetchOptions } from '#app' export function requestCore(url: string, options: UseFetchOptions) { // Const config = useRuntimeConfig() const { $mitt } = useNuxtApp() return useFetch(url, { baseURL: 'https://cantyonion.site', retry: false, timeout: 3000, onRequest({ options }) { let token = '' 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}`) } // 业务code状态码判断 // If (response._data.code !== 200) { // // } }, onResponseError({ response }) { $mitt.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() if (result.status.value === 'success') { return result.data.value } throw result.error } result = await requestCore(url, { method: 'GET', ...options, }) as AsyncData return result.data.value } }