92 lines
2.7 KiB
JavaScript
92 lines
2.7 KiB
JavaScript
const { envVersion } = wx.getAccountInfoSync().miniProgram;
|
||
let env='';
|
||
if(envVersion=="develop" || envVersion=="trial"){
|
||
env = require('./config').dev
|
||
}else{
|
||
env = require('./config').prod
|
||
};
|
||
class HTTP {
|
||
constructor() {
|
||
this.baseUrl = env.baseUrl,
|
||
this.staticHost = env.staticHost,
|
||
this.IMappId = env.IMappId,
|
||
this.IMsecretkey = env.IMsecretkey
|
||
}
|
||
|
||
request({
|
||
url,
|
||
data = {},
|
||
method = 'GET',
|
||
contentType = 'application/x-www-form-urlencoded',
|
||
showLoading = true
|
||
}){
|
||
return new Promise((resolve, reject) => {
|
||
this._request(url, resolve, reject, data, method, contentType, showLoading)
|
||
})
|
||
}
|
||
|
||
_request(url, resolve, reject, data = {}, method = 'GET', contentType = 'application/x-www-form-urlencoded', showLoading = true) {
|
||
if(showLoading) wx.showLoading();
|
||
let usertype = wx.getStorageSync('usertype');
|
||
wx.request({
|
||
url: url,
|
||
method: method,
|
||
data: data,
|
||
header: {
|
||
'content-type': contentType,
|
||
'Authorization': "Bearer " + wx.getStorageSync('AUTH_TOKEN_'+usertype)
|
||
},
|
||
success: (res) => {
|
||
// console.log("header Authorization: ", res.header.Authorization);
|
||
var Authorization_token = res.header.Authorization;
|
||
if(Authorization_token){
|
||
wx.setStorageSync('AUTH_TOKEN_'+usertype, Authorization_token);//当token快过期时,服务器会返回新token,本地刷新
|
||
}
|
||
if (res.data) {
|
||
const code = res.data.code;
|
||
if (code == 200) {
|
||
resolve(res.data)
|
||
} else if(code == 401 || code == 403 || code == 405 || code == 406){
|
||
wx.navigateTo({
|
||
url: "/Pages/login/index"
|
||
})
|
||
} else {
|
||
reject(res.data.message);//向后传递错误信息,catch会拿到
|
||
this._show_error(showLoading, res.data.message)
|
||
}
|
||
} else {
|
||
reject(res.data)//向后传递错误信息,catch会拿到
|
||
this._show_error(showLoading, err.data.message)
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
reject(err)//向后传递错误信息,catch会拿到
|
||
this._show_error(showLoading, err.data.message)
|
||
},
|
||
complete: (res) => {
|
||
// console.log("res from cmplete: ",res)
|
||
const code = res.data.code;
|
||
if (code == 200) {
|
||
if(showLoading) wx.hideLoading();
|
||
}
|
||
}
|
||
})
|
||
}
|
||
|
||
_show_error(showLoading, _message) {
|
||
if(showLoading) wx.hideLoading();
|
||
if(_message == undefined){
|
||
_message = "网络错误";
|
||
}
|
||
wx.showToast({
|
||
title: `${_message}`,
|
||
icon: 'none',
|
||
duration: 2000
|
||
})
|
||
}
|
||
}
|
||
|
||
export {
|
||
HTTP
|
||
}
|