引入
let Request = require("../"); //导入模块
get/post
Request.post('', //调用方法
{
}, {
'content-type': 'application/json', // 默认值
},
).then(res => { //成功回调
}).catch(err => {}) //异常回调
上传
Request.upload('', //调用方法
{
name
}, {
filePath
}, {
'content-type': 'multipart/form-data',
},
).then(res => { //成功回调
}).catch(err => {}) //异常回调
整体代码
function fun(url, method, data, header) {
data = data || {};
header = header || {};
let sessionId = wx.getStorageSync("UserSessionId");
if (sessionId) {
if (!header || !header["SESSIONID"]) {
header["SESSIONID"] = sessionId;
}
}
wx.showNavigationBarLoading();
let promise = new Promise(function (resolve, reject) {
wx.request({
url: apiHttp + url,
header: header,
data: data,
method: method,
success: function (res) {
if (res.statusCode == 401) {
wx.redirectTo({
url: '/pages/login/login',
})
}
if (res.statusCode == 200) {
if (res.data.code == 0) {
resolve(res);
} else {
wx.showToast({
title: "请求错误",
icon: 'none'
})
}
}
},
fail: reject,
complete: function () {
wx.hideNavigationBarLoading();
}
});
});
return promise;
}
function upload(url, name, filePath) {
let header = {};
let sessionId = wx.getStorageSync("UserSessionId"); //从缓存中拿该信息
if (sessionId) {
if (!header || !header["SESSIONID"]) {
header["SESSIONID"] = sessionId; //添加到请求头中
}
}
wx.showNavigationBarLoading();
let promise = new Promise(function (resolve, reject) {
wx.uploadFile({
url: apiHttp + url,
filePath: filePath,
name: name,
header: header,
success: function (res) {
resolve(res);
},
fail: reject,
complete: function () {
wx.hideNavigationBarLoading();
}
});
});
return promise;
}
module.exports = {
apiHttp: apiHttp,
"get": function (url, data, header) {
return fun(url, "GET", data, header);
},
"post": function (url, data, header) {
return fun(url, "POST", data, header);
},
upload: function (url, name, filePath) {
return upload(url, name, filePath);
}
};