| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788 |
- import axios, {
- AxiosError,
- AxiosHeaders,
- AxiosRequestConfig,
- AxiosResponse,
- InternalAxiosRequestConfig
- } from '@ohos/axios';
- import { IBestToast, YTLog } from '../../../../Index';
- import { AppStorageKeyCollect } from '../constants';
- import { userInfo } from '../models/UserInfo';
- import { yTRouter } from '../utils/YTRouter';
- // export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
- export const baseURL: string = 'http://192.168.1.160:9900'
- export const instance = axios.create({
- baseURL,
- timeout: 5000
- })
- // 添加请求拦截器
- instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
- // 对请求数据做点什么
- if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
- config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
- }
- return config;
- }, (error: AxiosError) => {
- // 对请求错误做些什么
- return Promise.reject(error);
- });
- // 添加响应拦截器
- instance.interceptors.response.use((response: AxiosResponse) => {
- // 对响应数据做点什么
- YTLog.info(response)
- // 对响应错误做点什么
- if (response.data.code == 401) {
- userInfo.logout()
- yTRouter.router2LoginPage()
- return Promise.reject('401');
- }
- if (response.data.code == 500) {
- IBestToast.show({ message: response.data.msg, type: "fail" })
- return Promise.reject(response.data);
- }
- return response.data.data;
- }, (error: AxiosError) => {
- YTLog.error(error)
- setTimeout(() => {
- IBestToast.hide()
- setTimeout(() => {
- IBestToast.show({ message: '请求超时,请检查网络' })
- }, 100)
- }, 1000)
- return Promise.reject(error);
- });
- export class YTRequest {
- static get<T>(url: string, params?: Record<string, string | number | boolean>, headers?: Record<string, string>) {
- return instance.get<null, T, null>(url, { params, headers })
- }
- static post<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
- return instance.post<null, T, D>(url, data, { params, headers })
- }
- static delete<T>(url: string, params?: Record<string, string | number | boolean> | object, headers?: AxiosHeaders) {
- return instance.delete<null, T, null>(url, { params, headers })
- }
- static put<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
- return instance.put<null, T, D>(url, data, { params, headers })
- }
- static upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
- return instance.post<string, T, D>(url, data, configs)
- }
- }
|