request.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. /**
  2. * HTTP请求封装
  3. */
  4. import { getToken } from './auth';
  5. import { API_BASE_URL } from './config';
  6. interface RequestOptions {
  7. url: string;
  8. method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
  9. data?: any;
  10. header?: Record<string, string>;
  11. showLoading?: boolean;
  12. showError?: boolean;
  13. }
  14. interface Response<T = any> {
  15. code: number;
  16. message: string;
  17. data: T;
  18. }
  19. /**
  20. * 发起HTTP请求
  21. */
  22. export function request<T = any>(options: RequestOptions): Promise<T> {
  23. const { url, method = 'GET', data, header = {}, showLoading = true, showError = true } = options;
  24. if (showLoading) {
  25. uni.showLoading({ title: '加载中...', mask: true });
  26. }
  27. const token = getToken();
  28. if (token) {
  29. header['adminAccessToken'] = token;
  30. }
  31. header['Content-Type'] = 'application/json';
  32. return new Promise((resolve, reject) => {
  33. uni.request({
  34. url: `${API_BASE_URL}${url}`,
  35. method,
  36. data,
  37. header,
  38. success: (res: any) => {
  39. if (showLoading) {
  40. uni.hideLoading();
  41. }
  42. const response = res.data as Response<T>;
  43. if (response.code === 200) {
  44. resolve(response.data);
  45. } else if (response.code === 401) {
  46. // Token过期,跳转登录
  47. uni.removeStorageSync('admin_token');
  48. uni.reLaunch({ url: '/pages/login/login' });
  49. reject(new Error('登录已过期'));
  50. } else {
  51. if (showError) {
  52. uni.showToast({
  53. title: response.message || '请求失败',
  54. icon: 'none'
  55. });
  56. }
  57. reject(new Error(response.message));
  58. }
  59. },
  60. fail: (err) => {
  61. if (showLoading) {
  62. uni.hideLoading();
  63. }
  64. if (showError) {
  65. uni.showToast({
  66. title: '网络请求失败',
  67. icon: 'none'
  68. });
  69. }
  70. reject(err);
  71. }
  72. });
  73. });
  74. }
  75. /**
  76. * GET请求
  77. */
  78. export function get<T = any>(url: string, data?: any): Promise<T> {
  79. return request<T>({ url, method: 'GET', data });
  80. }
  81. /**
  82. * POST请求
  83. */
  84. export function post<T = any>(url: string, data?: any): Promise<T> {
  85. return request<T>({ url, method: 'POST', data });
  86. }
  87. /**
  88. * PUT请求
  89. */
  90. export function put<T = any>(url: string, data?: any): Promise<T> {
  91. return request<T>({ url, method: 'PUT', data });
  92. }
  93. /**
  94. * DELETE请求
  95. */
  96. export function del<T = any>(url: string, data?: any): Promise<T> {
  97. return request<T>({ url, method: 'DELETE', data });
  98. }