//微信小程序请求函数的封装
const BASE_URL = "XXXXXXXXXXXXXXXXXXXX";
class Request {
/**
* Request请求方法
* @param {String} url 链接
* @param {Objece} params 参数
* @param {Boolean} isToken 是否携带token
* @return {Promise} 包含抓取任务的Promise
*/
getApi(url, params, isToken, isbinding,isshowerror) {
if (isToken === undefined) isToken = true;
if (isbinding === undefined) isbinding = true;
if (isshowerror === undefined) isshowerror = false;
let token = wx.getStorageSync('token') || '';
let uKey = wx.getStorageSync('uKey') || '';
const promise = new Promise((resolve, reject) => {
//判断是否需要置入token
if (isToken) params = Object.assign({sessionId:token}, params)
wx.request({
url: `${BASE_URL}${url}`,
method: 'POST',
data: params, //置入token
header: { 'Content-Type': 'application/x-www-form-urlencoded', 'token': token, 'uKey': uKey },
success: res => {
console.log(res);
if (res.statusCode == 200) {
if(res.data.code ==1){
resolve(res);
}else if(res.data.code ==2){
wx.navigateTo({
url: '/pages/login/index',
})
}else{
wx.showToast({
title: res.data.desc,
icon:'none',
duration:800
})
}
} else {
wx.showToast({
title: '[' + res.code + '] 服务器出错,请重试',
icon: 'none',
duration:800
});
reject();
}
},
fail: err => {
wx.showToast({
title: '网络错误',
icon: 'none',
duration:800
});
reject();
},
complete: res => {
}
});
});
if (token == '' && isToken) {
return new Promise((resolve, reject) => {
wx.showToast({
title: '状态失效,请关闭小程序后,重新打开',
icon: 'none'
});
});
} else {
return promise;
}
}
}
let request = new Request();
module.exports = {
post: request.getApi,
url: BASE_URL
}
//微信小程序请求函数的引用
/**
* 登录
* @return {Promise}
*/
login(params) {
return request.post(`/XXXXXXXXXXX`,params,false).then(res => res.data)
}
/**
* 获取问题列表和内容
* @return {Promise}
*/
question(params) {
return request.post(`/XXXXXXXXXXX`,params).then(res => res.data)
}