import { useMemberStore } from "@/store/modules/member"; import ENV_CONFIG from "../config/env"; import pinia from "@/store"; // 基础地址 let baseUrl = ""; // #ifdef H5 (process.env as any).config = ENV_CONFIG; // #endif const store = useMemberStore(pinia); baseUrl = (process.env as any).config[(process.env as any).NODE_ENV].VITE_APP_BASE_URL; const obj = { // 拦截前触发 invoke(options: UniApp.RequestOptions) { // 超时时间 options.timeout = 10000; // 拼接完整路径 if (!options.url.startsWith("http")) { if ('/prod/gateway/api/db/getDbInfo' !== options.url) { options.url = baseUrl + store.profile.childPath + options.url; } else { options.url = baseUrl + options.url; } } // 请求头标识 // 1.小程序唯一标识 // 'source-client': 'miniapp' options.header = { ...options.header }; options.header["source-client"] = "miniapp"; // 2.注入token // 2.1 获取token const token = store.profile?.token; if (token) { options.header["x-userToken"] = token; } }, }; // 请求拦截器 uni.addInterceptor("request", obj); uni.addInterceptor("uploadFile", obj); interface Data { code: string | number; data: T; msg: string; result: T; message: string; } // 响应拦截器 /*** * 1001: 未登录 * 1002: 登陆过期 */ export const http = (options: UniApp.RequestOptions) => { return new Promise>((resolve, reject) => { console.log(options); if ((options as any).header?.type === "UPLOAD") { uni.uploadFile({ header: { "x-userToken": store.profile?.token, // #ifdef H5 "Content-Type": "multipart/form-data", // #endif }, url: baseUrl + options.url, //仅为示例,非真实的接口地址 fileType: "image", // #ifdef H5 files: (options as any).data.files, // #endif // #ifdef MP-WEIXIN filePath: (options as any).data.path, // #endif name: "file", formData: { file: (options as any).data.files, }, // HTTP 请求中其他额外的 form data success: (res) => { resolve(JSON.parse(res.data) as Data); }, fail(err) { console.log(err); resolve(err as any); }, }); } else { uni.request({ ...options, dataType: "string", //1.先将dataType设置为string success(res) { var json = (res.data as any).replace( /:s*([0-9]{15,})s*(,?)/g, ': "$1" $2' ); //2.根据后端返回的数据调用一次或者两次replace替换 var json1 = json.replace(/:s*([0-9]{15,})s*(,?)/g, ': "$1" $2'); //3.手动转换回json数据即可 let res1: any = JSON.parse(json1); console.log(res1); if (res.statusCode >= 200 && res.statusCode < 300) { if ( res1.code === 1001 || res1.code === 1002 || res1.code === 1003 || res1.code === 1004 ) { uni.showToast({ icon: "none", title: (res1 as Data).message || "请求失败", }); store.clearProfile(); uni.reLaunch({ url: "/pagesLogin/login/index", }); return; } else if ((res1 as any).code === 10001) { uni.showToast({ icon: "none", title: (res1 as Data).message || "请求失败", }); return; } else if ((res1 as any).code === 5001) { uni.showToast({ icon: "none", title: (res1 as Data).message || "请求失败", }); } resolve(res1 as Data); } else { uni.showToast({ icon: "none", title: (res1 as any).msg || "请求失败", }); reject(res1); } }, fail(err) { uni.showToast({ icon: "none", title: "网络错误,请检查网络", }); reject(err); }, }); } }); };