const requestModule = import.meta.env.VITE_REQUEST_MODULE const requestBaseUrl = import.meta.env.VITE_BASE_URL const imgUrl = import.meta.env.VITE_BASE_IMG_URL function request(isDomain, url, method, data, header = {}, hideErrMsg = false, showLoading = false) { if (showLoading) { uni.showLoading({ title: '加载中...', icon: 'loading' }) } let urlLin = (requestModule + '/' + url).replace('//', '/') if (isDomain) { urlLin = url } else { // #ifndef H5 urlLin = requestBaseUrl + '/' + urlLin // #endif } if (header['Content-Type'] && (header['Content-Type'].includes('application/x-www-form-urlencoded') || header['Content-Type'].includes('multipart/form-data'))) { data = createFormData(data) } const token = uni.getStorageSync('token') if (token) { header['Manage-Token'] = token } return new Promise((resolve, reject) => { uni.request({ url: urlLin, method: method, data: data, header: { 'Content-Type': 'application/json', ...header }, success: function(res) { console.log('success::::', res) if (res.statusCode !== 200) { if (!hideErrMsg) { uni.showToast({ title: parseStatusCodeErrMsg(res.statusCode), icon: 'none', duration: 2000 }) } reject(res) } else if (!res.data.errorCode || res.data.errorCode === '0') { resolve(res.data) } else if (res.data.errorCode === '10009') { uni.navigateTo({ url: '/pages/login/index' }) } else { if (!hideErrMsg) { uni.showToast({ title: res.data.errorDetails, icon: 'error', duration: 2000 }) } reject(res) } }, fail: function(res) { if (!hideErrMsg) { uni.showToast({ title: '请求错误', icon: 'none', duration: 2000 }) } reject(res) }, complete: function() { if (showLoading) { uni.hideLoading() } } }) }) } const parseStatusCodeErrMsg = (statusCode) => { if (statusCode === 200) { return '' } else if (statusCode === 404) { return '服务器资源不存在' } else if (statusCode === 403) { return '服务器资源禁止访问' } else if (statusCode === 502) { return '服务器无响应' } else if (statusCode === 504) { return '服务器响应超时' } else if (statusCode === 599) { return '网络链接超时' } else { return '服务器响应错误' } } function createFormData(obj = {}) { let formDataString = '' for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { if (Array.isArray(obj[key])) { // 处理数组属性 for (const value of obj[key]) { formDataString += `${key}[]=${encodeURIComponent(value)}&` } } else { // 处理普通属性 formDataString += `${key}=${encodeURIComponent(obj[key])}&` } } } // 去掉末尾的 '&' formDataString = formDataString.slice(0, -1) return formDataString } function get(obj) { return request(obj.isDomain, obj.url, 'GET', obj.data, obj.header, obj.hideErrMsg, obj.showLoading) } function post(obj) { return request(obj.isDomain, obj.url, 'POST', obj.data, obj.header, obj.hideErrMsg, obj.showLoading) } function formPost(obj) { return request(obj.isDomain, obj.url, 'POST', obj.data, { ...obj.header, 'Content-Type': 'application/x-www-form-urlencoded' }, obj.hideErrMsg, obj.showLoading) } export default { imgUrl, request, get, post, formPost }
封装的request请求方法
最新推荐文章于 2024-08-13 09:40:14 发布