import axios, { AxiosRequestConfig, AxiosRequestHeaders, AxiosResponse } from 'axios' import { IResponseData } from './types' import { ElMessage, ElLoading, ILoadingInstance } from 'element-plus' type TAxiosOption = { baseURL: string; timeout: number; } const config = { baseURL: '/api', timeout: 5000 } let loading: ILoadingInstance; class Http { // service: AxiosInstance; service; constructor(config: TAxiosOption) { this.service = axios.create(config) /* 請求攔截 this.service.interceptors.request.use(config => config, error => Promise.reject(error))*/ this.service.interceptors.request.use((config: AxiosRequestConfig) => { loading = ElLoading.service({ lock: true, text: '加載中~~~~', // spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)', }) if (localStorage.getItem('token')) { (config.headers as AxiosRequestHeaders).authorization = localStorage.getItem('token') as string } return config }, error => { loading.close() console.log("error"); return Promise.reject(error) // 為了可以在代碼中catch到錯誤信息 }) /* 響應攔截 this.service.interceptors.response.use(response => response.data, error => Promise.reject(error))*/ this.service.interceptors.response.use((response: AxiosResponse<any>) => { ElMessage.success('請求成功',) loading.close() const data = response.data return response.data }, error => { loading.close() ElMessage.error('請求失敗',) return Promise.reject(error) }) } get<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.get(url, { params, ..._object }) } post<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.post(url, params, _object) } put<T>(url: string, params?: object, _object = {}): Promise<IResponseData<T>> { return this.service.put(url, params, _object) } delete<T>(url: string, params?: any, _object = {}): Promise<IResponseData<T>> { return this.service.delete(url, { params, ..._object }) } } export default new Http(config)