interface RequestHeader { 'Content-Type': string; 'Authorization'?: string; [key: string]: string | undefined; } interface RequestOptions extends WechatMiniprogram.RequestOption { loading?: boolean; } interface ResponseData { code: number; message: string; data: T; time?: string; } const baseURL = 'http://localhost:8084/api'; const request = { async request(options: RequestOptions): Promise> { const token = wx.getStorageSync('token'); console.log(token); // 定义header类型 const header: RequestHeader = { 'Content-Type': 'application/json', ...options.header, }; // 统一添加token if (token) { console.log('Token值:', token); header['Authorization'] = `Bearer ${token}`; console.log('完整Authorization:', header['Authorization']); } if (options.loading) { wx.showLoading({ title: '加载中...', mask: true }); } try { console.log('发送请求的header:', header); const res = await new Promise((resolve, reject) => { wx.request({ url: baseURL + options.url, method: options.method, data: options.data, header, success: (res) => { console.log('请求响应:', res); // 先检查状态码 if (res.statusCode === 401) { // 清除本地token wx.removeStorageSync('token'); wx.removeStorageSync('userInfo'); // 跳转到登录页 wx.redirectTo({ url: '/pages/login/index' }); reject(new Error('登录已过期,请重新登录')); return; } resolve(res); }, fail: reject }); }); const data = res.data as ResponseData; // 检查业务状态码 if (data.code !== 200) { throw new Error(data.message || '请求失败'); } return data; } catch (error) { console.error('请求错误:', error); // 统一错误提示 wx.showToast({ title: error instanceof Error ? error.message : '请求失败', icon: 'none' }); throw error; } finally { if (options.loading) { wx.hideLoading(); } } }, // GET请求 get(url: string, data?: object, options: Partial = {}): Promise> { return this.request({ method: 'GET', url, data, ...options }); }, // POST请求 post(url: string, data?: object, options: Partial = {}): Promise> { return this.request({ method: 'POST', url, data, ...options }); }, // PUT请求 put(url: string, data?: object, options: Partial = {}): Promise> { return this.request({ method: 'PUT', url, data, ...options }); }, // DELETE请求 delete(url: string, data?: object, options: Partial = {}): Promise> { return this.request({ method: 'DELETE', url, data, ...options }); } }; export default request;