You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

112 lines
3.0 KiB

const app = getApp()
let flag = false
const obj = { //这里是要导出的函数
xhr: function ({url = '',method = 'get',header = {}, data = {},baseUrl = app.globalData.serverUrl}) {
let token = wx.getStorageSync('token')
header = {
'Content-Type': 'application/json',
}
if (token) {
header['Authorization'] = `Bearer ${token}`
}
return new Promise((resolve, rejects) => {
wx.request({
url: `${baseUrl}${url}`,
method,
header,
data,
success: res => {
if (res.data.code == 1 || res.data.code == 0||res.data.code == 2||res.data.code==3) {
resolve(res.data)
// wx.hideLoading()
} else if (res.data.code == 401) {
wx.showLoading({
title: '正在登录...',
})
if (flag) {
return
}
flag = true
if (token) { // token失效
flag = false
this.login_fn().then(res => {
wx.hideLoading()
let shareType = wx.getStorageSync('shareType'),userId = wx.getStorageSync('userId')
if(shareType && userId) app.share_add_integral(shareType,userId)
return this.xhr({url,data,method}).then(res => {
resolve(res)
wx.hideLoading()
})
})
} else { // 新用户
flag = false
wx.hideLoading()
wx.navigateTo({
url: '/pages/login/login',
})
}
} else {
console.log(res,'未知错误')
}
},
fail: err => {
rejects(err)
wx.hideLoading()
}
})
})
},
login_fn() {
return new Promise((resolve, rejects) => {
let loginUserInfo = wx.getStorageSync('loginUserInfo');
if (loginUserInfo) {
wx.login({
success: e => {
let code = e.code;
this.xhr({
url: 'api/v1/login',
method: 'post',
data: {
jsCode: code,
wxUnifyUserAddInput: loginUserInfo
}
}).then(res => {
wx.setStorageSync('token', res.data.token);
wx.setStorageSync('loginUserInfo', loginUserInfo)
resolve(res)
// this.get_user_msg()
}).catch(err => {
rejects(err)
})
}
})
} else {
let pages = getCurrentPages(),
currentPage = pages[pages.length - 1];
currentPage.setData({
is_show_login: true
})
}
})
},
get_user_msg(){
return new Promise((resolve,rejects) => {
this.xhr({
url: `api/v1/user/unreadinformation`
}).then(res => {
resolve(res)
wx.setStorageSync('msg', res.data)
}).catch(err => {
rejects(err)
})
})
},
}
wx.axios = obj.xhr
module.exports = obj