YTRequest.ets 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import axios, {
  2. AxiosError,
  3. AxiosHeaders,
  4. AxiosRequestConfig,
  5. AxiosResponse,
  6. InternalAxiosRequestConfig
  7. } from '@ohos/axios';
  8. import { IBestToast, YTLog } from '../../../../Index';
  9. import { AppStorageKeyCollect } from '../constants';
  10. import { userInfo } from '../models/UserInfo';
  11. import { yTRouter } from '../utils/YTRouter';
  12. // export const baseURL: string = 'https://hm-test.ytpm.net/prod-api'
  13. export const baseURL: string = 'http://192.168.1.160:9900'
  14. export const instance = axios.create({
  15. baseURL,
  16. timeout: 5000
  17. })
  18. // 添加请求拦截器
  19. instance.interceptors.request.use((config: InternalAxiosRequestConfig) => {
  20. // 对请求数据做点什么
  21. if (AppStorage.get<string>(AppStorageKeyCollect.TOKEN)) {
  22. config.headers.Authorization = AppStorage.get<string>(AppStorageKeyCollect.TOKEN)
  23. }
  24. return config;
  25. }, (error: AxiosError) => {
  26. // 对请求错误做些什么
  27. return Promise.reject(error);
  28. });
  29. // 添加响应拦截器
  30. instance.interceptors.response.use((response: AxiosResponse) => {
  31. // 对响应数据做点什么
  32. YTLog.info(response)
  33. // 对响应错误做点什么
  34. if (response.data.code == 401) {
  35. userInfo.logout()
  36. yTRouter.router2LoginPage()
  37. return Promise.reject('401');
  38. }
  39. if (response.data.code == 500) {
  40. IBestToast.show({ message: response.data.msg, type: "fail" })
  41. return Promise.reject(response.data);
  42. }
  43. return response.data.data;
  44. }, (error: AxiosError) => {
  45. YTLog.error(error)
  46. setTimeout(() => {
  47. IBestToast.hide()
  48. setTimeout(() => {
  49. IBestToast.show({ message: '请求超时,请检查网络' })
  50. }, 100)
  51. }, 1000)
  52. return Promise.reject(error);
  53. });
  54. export class YTRequest {
  55. static get<T>(url: string, params?: Record<string, string | number | boolean>, headers?: Record<string, string>) {
  56. return instance.get<null, T, null>(url, { params, headers })
  57. }
  58. static post<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
  59. return instance.post<null, T, D>(url, data, { params, headers })
  60. }
  61. static delete<T>(url: string, params?: Record<string, string | number | boolean> | object, headers?: AxiosHeaders) {
  62. return instance.delete<null, T, null>(url, { params, headers })
  63. }
  64. static put<T, D>(url: string, data?: D, params?: Record<string, string | number | boolean>, headers?: AxiosHeaders) {
  65. return instance.put<null, T, D>(url, data, { params, headers })
  66. }
  67. static upPost<T, D>(url: string, data: D, configs?: AxiosRequestConfig<D>) {
  68. return instance.post<string, T, D>(url, data, configs)
  69. }
  70. }