// 线上域名 // const host = "https://www.xiaoyaotravel.com/api" // 测试服务器域名 // const host = "http://test.xiaoyaotravel.com:8082"; // 测试服务器ip const host = "http://101.126.146.250:8082"; // 黄雯本地 // const host ="http://192.168.1.109:8082" // const host ="http://q9943037p3.goho.co" // 李忠畅本地 // const host = "http://192.168.1.100:8082" // const host ="http://cilicli.qicp.vip" const request = ({ url, data, header, method = "GET", showLoading = true, showErrorToast = true, } = {}) => { return new Promise((resolve, reject) => { const token = getToken(); if (showLoading) uni.showLoading({ title: "加载中" }); uni.request({ // url: `${import.meta.env.VITE_API_BASE_URL}${url}`, url: `${host}${url}`, method, data, header: { ...header, Authorization: token, version: "1.0" }, success: (res) => handleSuccessCallback({ res, resolve, reject, showLoading, showErrorToast, }), fail: (_) => handleFailCallback({ reject }), }); }); }; // 上传文件 const upload = ({ url, filePath, name }) => { return new Promise((resolve, reject) => { uni.showLoading({ title: "加载中" }); uni.uploadFile({ url: `${host}${url}`, header: { token: "" }, filePath, name, success: (res) => handleSuccessCallback({ res, resolve, reject }), fail: (_) => handleFailCallback({ reject }), }); }); }; const handleSuccessCallback = ({ res, resolve, reject, showLoading = true, showErrorToast = true, }) => { if (showLoading) uni.hideLoading(); let { statusCode, data } = res; const isSuccess = isHTTPSuccess(statusCode); if (!isSuccess) { if (showErrorToast) uni.showToast({ icon: "none", title: "网络错误请重新尝试" }); reject({ msg: `网络错误${statusCode}`, detail: res }); } if (isJSONString(data)) data = JSON.parse(data); if (data.errorCode === "NO-ERROR") { // 业务处理成功 resolve(data); } else if (data.errorCode === "UNAUTHORIZED_LOGIN") { uni.$u.toast('请登录!') setTimeout(()=>{ uni.navigateTo({ url:'/pages/index/login' }) },1000) // 登录过期 // const { gotoLogin, setToken } = useAuth(); // setToken(""); // gotoLogin(); // reject({ msg: data.msg, detail: res }); } else { if (showErrorToast) uni.showToast({ icon: "none", title: data.errorMessage }); reject({ msg: data.errorMessage, detail: res }); } }; const handleFailCallback = ({ reject, showLoading = true, showErrorToast = true, }) => { if (showLoading) uni.hideLoading(); if (showErrorToast) { uni.showToast({ icon: "none", title: "网络错误请重新尝试" }); } reject({ msg: "网络错误", detail: null }); }; /** * 判断请求状态是否成功 * 参数:http状态码 * 返回值:[Boolen] */ const isHTTPSuccess = (status) => { return (status >= 200 && status < 300) || status === 304; }; const isJSONString = (str) => { if (typeof str === "string") { try { JSON.parse(str); return true; } catch (error) { return false; } } return false; }; export { request, upload };