import { base_url, appId } from '@/utils/config.js'; import {urlEncode} from '@/utils/utils.js'; import store from '../store/index.js'; //封装的通用请求方法 export const axios = function(obj = {}) { if (typeof obj !== 'object') { throw new Error('arguments must be object'); } if (!obj.url) { throw new Error('url not defined'); } return new Promise((resolve, reject) => { if (obj.isLoading) { uni.showLoading({ title: '加载中', mask: true, }) } let _url = base_url + obj.url; let isGet = obj.method && obj.method.toLowerCase() == 'get'; if(isGet){ _url += '?'+ urlEncode(obj.params) } uni.request({ url: _url, data: isGet ? '' : (obj.params || ''), header: { 'content-type': obj.type || 'application/x-www-form-urlencoded', "x-token": uni.getStorageSync('token') || '', 'APPID': appId }, method: obj.method ? obj.method : "POST", success: function(res) { if (obj.isLoading) { uni.hideLoading(); } if (res.statusCode === 200) { if (res.data.code == 200 || res.data.code == 1100) { resolve(res.data) } else if (res.data.code == 1001) { uni.showToast({ title: '未登录', icon: 'none' }); store.commit('changeIsLogin', false); uni.removeStorageSync('token'); uni.navigateTo({ url: '/pages/login/index', }) reject(res.data); } else { uni.showToast({ title: res.data.message, icon: 'none' }); reject(res.data); } } else { uni.showToast({ title: '错误码:' + res.statusCode, icon: 'none' }) reject(res.data); } }, fail: function(err) { uni.showModal({ title:'提示', content: '网络连接失败'+JSON.stringify(err), }) reject(err); }, }) }) } const getUUID = function(){ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => { return (c === 'x' ? (Math.random() * 16) | 0 : 'r&0x3' | '0x8').toString(16) }) } const createName = function(name){ const date = Date.now() const uuid = getUUID() const fileSuffix = name.substring(name.lastIndexOf('.') + 1) return `${date}${uuid}.${fileSuffix}` } // 图片上传 export const uploadImg = async function(file) { console.log(file); uni.showLoading({ mask: true, }) // 获取oss配置 const par = await axios({ url: '/common/oss/config', method: 'get' }).then(res=>{ return res.data; }).catch(err=>{ uni.hideLoading(); }) const fileKey = par.dir + createName(file.path); return new Promise((resolve, reject) => { uni.uploadFile({ url: par.host, // header: { // "Content-Type": 'multipart/form-data', // }, name: 'file', formData:{ ...par, name: file.name, key: fileKey }, filePath: file.path, success(res) { resolve({ url: fileKey }) }, fail(err) { reject(err) }, complete(res) { uni.hideLoading(); } }) }) } export default { axios, uploadImg, }