// API配置和请求封装 const BASE_URL = 'http://localhost:8888' // gva后端地址 class Api { constructor() { this.baseURL = BASE_URL } // 通用请求方法 request(options) { return new Promise((resolve, reject) => { // 获取token const token = uni.getStorageSync('token') uni.request({ url: this.baseURL + options.url, method: options.method || 'GET', data: options.data || {}, header: { 'Content-Type': 'application/json', 'Authorization': token ? `Bearer ${token}` : '', ...options.header }, success: (res) => { if (res.statusCode === 200) { if (res.data.code === 0) { resolve(res.data) } else { reject(new Error(res.data.msg || '请求失败')) } } else if (res.statusCode === 401) { // token过期,跳转登录 uni.removeStorageSync('token') uni.reLaunch({ url: '/pages/login/login' }) reject(new Error('登录已过期')) } else { reject(new Error('网络错误')) } }, fail: (err) => { reject(new Error('网络连接失败')) } }) }) } // GET请求 get(url, data) { return this.request({ url, method: 'GET', data }) } // POST请求 post(url, data) { return this.request({ url, method: 'POST', data }) } // PUT请求 put(url, data) { return this.request({ url, method: 'PUT', data }) } // DELETE请求 delete(url, data) { return this.request({ url, method: 'DELETE', data }) } } module.exports = new Api()