77 lines
2.0 KiB
JavaScript
77 lines
2.0 KiB
JavaScript
const env = require('./config').dev
|
||
|
||
class HTTP {
|
||
constructor() {
|
||
this.baseUrl = env.baseUrl,
|
||
this.staticHost = env.staticHost,
|
||
this.appId = env.appId
|
||
}
|
||
|
||
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();
|
||
wx.request({
|
||
url: url,
|
||
method: method,
|
||
data: data,
|
||
header: {
|
||
'content-type': contentType,
|
||
'appId': this.appId,
|
||
'Authorization': "Bearer " + wx.getStorageSync('AUTH_TOKEN')
|
||
},
|
||
success: (res) => {
|
||
console.log("header Authorization: ", res.header.Authorization);
|
||
var Authorization_token = res.header.Authorization;
|
||
if(Authorization_token){
|
||
wx.setStorageSync('AUTH_TOKEN', 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/index/index"
|
||
})
|
||
} else {
|
||
reject(res.data.message)
|
||
this._show_error(res.data.message)
|
||
}
|
||
} else {
|
||
resolve(res.data)
|
||
}
|
||
},
|
||
fail: (err) => {
|
||
reject()
|
||
this._show_error(err.data.message)
|
||
},
|
||
complete: () => {
|
||
if(showLoading) wx.hideLoading();
|
||
}
|
||
})
|
||
}
|
||
|
||
_show_error(_message) {
|
||
wx.showToast({
|
||
title: `${_message}`,
|
||
icon: 'none',
|
||
duration: 2000
|
||
})
|
||
}
|
||
}
|
||
|
||
export {
|
||
HTTP
|
||
}
|