1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| import axios, { AxiosError, AxiosResponse, InternalAxiosRequestConfig } from '@ohos/axios' import { PreferencesManager } from '@yue/preferences_manager' import router from '@ohos.router';
const instance = axios.create({ baseURL: 'https://exapmle.com/api', timeout: 30000, headers: { 'client': 'app' } });
instance.interceptors.request.use((config: InternalAxiosRequestConfig) => { const token = PreferencesManager.defManager.get("access_token", "") if (token) { config.headers.Authorization = 'Bearer ' + token } return config; }, (error: AxiosError) => { return Promise.reject(error); });
instance.interceptors.response.use((response: AxiosResponse) => { return response.data }, (error: AxiosError) => { if (error.response?.status === 401) { router.pushUrl({ url: 'pages/Login' }) } return Promise.reject(error); });
export class HTTP { static request<T>(config: InternalAxiosRequestConfig): Promise<T> { return instance<null, T>(config) }
static get<T>(url: string, params?: object): Promise<T> { return instance.get<null, T>(url, { params }) }
static post<T>(url: string, data?: object, config?: object): Promise<T> { return instance.post<null, T>(url, data, config) }
static put<T>(url: string, data?: object): Promise<T> { return instance.put<null, T>(url, data) }
static delete<T>(url: string, data?: object): Promise<T> { return instance.delete<null, T>(url, { data }) } }
export default HTTP
|