import { hideLoading, showLoading } from './loading'; import { MyRequestOptions, HttpResponse } from './type/index'; import * as Pinia from 'pinia'; import { useUserStore } from '@/store'; const mapBaseUrl = { dev: "192.168.2.6", prod: "221.182.8.141" }; const port = "21088" export const BASE_URL = `http://${mapBaseUrl.prod}:${port}`; /** * 封装uni.request * @param {String} option.method 请求方式 * @param {String} option.url 请求url * @param {Object} option.data 请求参数 * @param {Object} option.loading loading配置信息 * @param {Boolean} option.loading.show 显示loading * 余下配置参考 RequestOptions 类型定义 * 如果要扩展 可在 MyRequestOptions 下进行类型扩展 * * ==== * MyRequestOptions HttpResponse 放在了./type/index.ts 建议放在 global.d.ts 全局 ts 类型定义中 * ==== * @returns */ const request = ( option : MyRequestOptions ) : Promise> => { const userStore = useUserStore(Pinia.createPinia()) const token = userStore.token || uni.getStorageSync('token') if (token !== '') { //Token不为空,请求参数默认增加Token参数 option['header']['X-Authorization'] = `Bearer ${token}` } else if (option.url !== '/base/api/auth/login') { uni.showToast({ title: '登录信息失效,请重新登录', duration: 1500, icon: 'none', success: function () { setTimeout(function () { uni.reLaunch({ url: '/pages/login/index' }) }, 1500) } }) } return new Promise((resolve, reject) => { // 处理请求loading if (option.loading?.show) { showLoading(option.loading.option); } uni.request({ method: option.method || 'GET', url: `${BASE_URL}${option.url}`, // 完整URL data: option.data || {}, header: option.header || {}, success: async (res) => { // 处理响应数据 if (option.loading?.show) { hideLoading(); } const data = res.data as HttpResponse; if (option.url === '/base/api/auth/login') { if (data?.token) { resolve(data); } else { uni.$msg('登录失败') reject() } } else if(option.url==='/base/api/yt/user/me/info'){ if (data?.username) { resolve(data); } else { uni.$msg('用户信息请求失败') reject() } } else { if (data.code === 200) { resolve(data); } else { uni.$msg(data.errMsg); reject() } if (data.code === 401) { uni.removeStorageSync('token') uni.removeStorageSync('userInfo') // 删除缓存 uni.reLaunch({ url: '/pages/login/index' }); } } }, fail: (err) => { if (option.loading?.show) { hideLoading(); } uni.$msg(err.errMsg); reject(err); } }); }); }; // 这里仅封装了部分常用的请求方法,可以根据需求继续封装其他方法 request.post = (option : MyRequestOptions) => { return request({ method: 'POST', ...option }) as unknown as Promise>; }; request.get = (option : MyRequestOptions) => { return request({ method: 'GET', ...option }) as unknown as Promise>; }; request.put = (option : MyRequestOptions) => { return request({ method: 'PUT', ...option }) as unknown as Promise>; }; request.delete = (option : MyRequestOptions) => { return request({ method: 'DELETE', ...option }) as unknown as Promise>; }; export default request;