import { baseURL } from './config.js' // 创建请求实例 const request = { // 通用请求方法 async request(options = {}) { let uniPlatform = uni.getSystemInfoSync().uniPlatform; let platform = uni.getSystemInfoSync().uniPlatform; let deviceOsversion = uni.getSystemInfoSync().osName+uni.getSystemInfoSync().osVersion; // 处理请求配置 const config = { url: options.url || '', method: options.method || 'GET', header: { 'content-type': 'application/json', ...options.header }, data: Object.assign({uniPlatform,platform,deviceOsversion}, options.data) || {uniPlatform,platform,deviceOsversion}, timeout: options.timeout || 60000, } // 添加token const token = uni.getStorageSync('token') if (token) { config.header.Authorization = token } try { // 发起请求 const response = await uni.request({ ...config, url: `${baseURL}${config.url}` }) // 处理响应 if (response.statusCode === 200) { const { code, data, msg } = response.data // 根据业务状态码处理 switch (code) { case 200: return data default: uni.showToast({ title: data || msg , icon: 'none' }) throw new Error(data || msg) } } else if (response.statusCode === 401) { if(!uni.getStorageSync('token')){ uni.reLaunch({ url: '/pages/login/index' }) return } else { uni.showToast({ title: '登录已过期,请重新登录', icon: 'none' }) uni.removeStorageSync('token') setTimeout(() => { uni.reLaunch({ url: '/pages/login/index' }) }, 1500) throw new Error('登录已过期,请重新登录') } } else { uni.showToast({ title: '网络错误', icon: 'none' }) throw new Error('网络错误') } } catch (error) { throw error || '服务器错误' } }, // GET请求 get(url, data = {}, options = {}) { return this.request({ url, method: 'GET', data, ...options }) }, // POST请求 post(url, data = {}, options = {}) { return this.request({ url, method: 'POST', data, ...options }) }, } export default request