个人封装示例
该方式主要是解决统一请求地址、函数中不干扰this问题
import Vue from 'vue'
let api = Vue.prototype.baseUrl
let user = uni.getStorageSync('userData')
let uid = ''
if(user) {
uid = user.userId
}
export default function request(url, method = 'GET', params = {}, successFun, failFun) {
url = api + url
uni.request({
url,
data: params,
method,
header: {
uid: uid
},
success(res) {
console.log(res);
successFun(res.data)
},
fail(err) {
failFun(err)
}
})
}
接口地址放在了main.js中
// Vue.prototype.baseUrl = 'https://fanmr.cn/handiness'
Vue.prototype.baseUrl = 'http://192.168.100.8:18090'
使用方式
import httpUtil from "../../common/httpUtil.js"
httpUtil('/app/update/last', 'POST', {}, (res) => {
console.log('成功', res);
}, (err) => {
console.log('失败', err);
this.$refs.uToast.show({message:'请求失败'})
})
文件上传(form-data)
// 获取头像
onChooseAvatar(e) {
// 上传头像到服务器
const tempFilePath = e.detail.avatarUrl;
let that = this
wx.uploadFile({
url: that.baseUrl + '/uploadFile',
filePath: tempFilePath,
name: 'file',
header: {
'content-type': 'multipart/form-data',
},
success(res) {
let resData = JSON.parse(res.data)
console.log(resData);
that.info.avatar = resData.data
that.avatarUrl = that.baseUrl + that.info.avatar
},
fail(error) {
console.log('upload failed', error);
}
});