// API配置信息 import urls from '../common/config.js' /** * 构建完整请求URL * @param {Object} path */ function buildUrl(path) { // 完整接口地址返回 if (path.startsWith('http://') || path.startsWith('https://')) { return path; } return urls.api + path; } /** * 通用请求封装 * @param {Object} path * @param {Object} data */ function postData(path, data) { // 构建完整请求 const url = buildUrl(path) return new Promise((resolve, reject) => { uni.request({ url: url, data: data, method: "POST", header: { 'content-type': "application/json", 'token': uni.getStorageSync("token"), 'mac': uni.getStorageSync("mac") // APP.vue页面的mac地址 }, success: function(res) { // 错误500 if (res.statusCode == 500) { uni.showToast({ title: '糟糕,服务器开小差了~', icon: 'none', duration: 5000 }); return; } // 404 if (res.statusCode == 404) { uni.showToast({ title: '接口地址404,请联系管理员~', icon: 'none', duration: 5000 }); return; } // 成功才回调 if (res.data.code === 0) { resolve(res.data.data); } else { // 后台错误信息 uni.showToast({ title: res.data.msg, icon: 'none', duration: 3000 }); if (res.data.code === 10010002) { // 跳转到登录 uni.navigateTo({ url: '/pages/login/login' }); return; } reject(res.data) } }, fail: function(e) { uni.showToast({ title: '啊哦,与服务器失去连接了~', icon: 'none', duration: 10000 }); } }); }); } /** * 文件上传 * @param {Object} url * @param {Object} file * @param {Object} data */ function uploadData(path, file, formData) { // 构建完整请求地址 let url = buildUrl(path) uni.showLoading({ title: '正在上传...' }) // 兼容chooseMedia const filePath = file.path || file.tempFilePath return new Promise((resolve, reject) => { uni.uploadFile({ url: url, filePath: filePath, name: 'file', header: { 'token': uni.getStorageSync("token") }, formData: formData, success: res => { let data = {} if (res.data) { data = JSON.parse(res.data) } resolve(data); uni.hideLoading() }, fail: err => { reject() uni.hideLoading() } }) }); } module.exports = { post: postData, upload: uploadData };