为了避免在小程序开发中使用大量重复且臃肿的代码,一般来说,开发者都会封装一个请求以便于直接调用,这里封装了一个简单简单的请求:
let maxLen = 6, // 批量删除图片的最大值
responseArr = []; // 存批量删除图片的响应数据
// 请求类封装
class _nb {
constructor () {
this.baseURL = "https://ln.talkingcake.com/app";
this.uploadURL = "https://ln.talkingcake.com/admin";
}
/*
* ajax 请求封装 author displayli 2019.05.27
* @path 路径
* @data requestBody
* @header null
* @method 请求方法 「默认为post」
* @dataType json
* @success 成功回调函数
* @fail 失败回调函数
*/
wxrequest({ path, data, header, method, dataType, success, fail }){
return new Promise((resolve, reject) => {
wx.request({
url: this.baseURL + path,
data: data || {},
header: header || {
"content-type": "application/json",
token: wx.getStorageSync("token") // 可有可无
},
method: method || "POST",
dataType: dataType || "json",
success: ({ data }) => {
// 如果code == 0 说明成功
if (!data.code) {
if (typeof success == 'function'){
success(data);
} else {
resolve(data);
}
} else {
// 否则有问题出现
wx.showToast({
title: data.msg,
icon: "none",
duration: 500
});
}
},
fail: err => {
if (typeof fail == 'function'){
fail(err);
} else {
reject(err);
}
console.error(new Error(err));
}
});
});
};
/*
* uplaod Image
*/
uploadImg({ count, path, sizeType, sourceType, success, title, icon}) {
return wx.chooseImage({
count: count || 1,
sizeType: sizeType || ['original', 'compressed'], // 可选择原图或压缩后的图片
sourceType: sourceType || ['album', 'camera'], // 可选择性开放访问相册、相机
success: res => {
setTimeout(() => {
wx.showToast({
title: title || "上传中...",
icon: icon || 'loading',
duration: 500
})
},800)
// 调用上传文件接口
this.uploadFiles({ path, files: res.tempFilePaths }).then(res => {
success(res); // 回调函数callback
})
}
})
}
// 上传文件方法
uploadFiles({path,files}){
let _this = this;
return new Promise((resolve, reject) => {
// 多文件上传需要遍历调接口 单个文件上传不需要遍历 直接循环去掉就好
files.forEach((item, index) => {
wx.uploadFile({
url: _this.uploadURL + path,
filePath: item,
header: {
'token': wx.getStorageSync('token') // 可有可无
},
name: 'img', // 上传文件规定的字段名
success(res) {
// 多文件上传获取响应值
responseArr.push(res.data.URL);
if (index == (files.length - 1)) {
resolve(responseArr)
}
// 单个文件
resolve(res.data)
},
fail(err) {
reject(err);
console.error(err);
}
})
})
})
}
}
// 对外公开
module.exports = {
_nb: new _nb()
};
当然你也可以直接将上面的三个方法直接写在app.js中,然后全局调用即可,这个仅仅是把它们以模块化的方式放在一个文件中而已
以上,请大家参考