| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- /**
- * HTTP请求封装
- */
- import { getToken } from './auth';
- import { API_BASE_URL } from './config';
- interface RequestOptions {
- url: string;
- method?: 'GET' | 'POST' | 'PUT' | 'DELETE';
- data?: any;
- header?: Record<string, string>;
- showLoading?: boolean;
- showError?: boolean;
- }
- interface Response<T = any> {
- code: number;
- message: string;
- data: T;
- }
- /**
- * 发起HTTP请求
- */
- export function request<T = any>(options: RequestOptions): Promise<T> {
- const { url, method = 'GET', data, header = {}, showLoading = true, showError = true } = options;
- if (showLoading) {
- uni.showLoading({ title: '加载中...', mask: true });
- }
- const token = getToken();
- if (token) {
- header['adminAccessToken'] = token;
- }
- header['Content-Type'] = 'application/json';
- return new Promise((resolve, reject) => {
- uni.request({
- url: `${API_BASE_URL}${url}`,
- method,
- data,
- header,
- success: (res: any) => {
- if (showLoading) {
- uni.hideLoading();
- }
-
- const response = res.data as Response<T>;
-
- if (response.code === 200) {
- resolve(response.data);
- } else if (response.code === 401) {
- // Token过期,跳转登录
- uni.removeStorageSync('admin_token');
- uni.reLaunch({ url: '/pages/login/login' });
- reject(new Error('登录已过期'));
- } else {
- if (showError) {
- uni.showToast({
- title: response.message || '请求失败',
- icon: 'none'
- });
- }
- reject(new Error(response.message));
- }
- },
- fail: (err) => {
- if (showLoading) {
- uni.hideLoading();
- }
- if (showError) {
- uni.showToast({
- title: '网络请求失败',
- icon: 'none'
- });
- }
- reject(err);
- }
- });
- });
- }
- /**
- * GET请求
- */
- export function get<T = any>(url: string, data?: any): Promise<T> {
- return request<T>({ url, method: 'GET', data });
- }
- /**
- * POST请求
- */
- export function post<T = any>(url: string, data?: any): Promise<T> {
- return request<T>({ url, method: 'POST', data });
- }
- /**
- * PUT请求
- */
- export function put<T = any>(url: string, data?: any): Promise<T> {
- return request<T>({ url, method: 'PUT', data });
- }
- /**
- * DELETE请求
- */
- export function del<T = any>(url: string, data?: any): Promise<T> {
- return request<T>({ url, method: 'DELETE', data });
- }
|