const baseUrl = "xxx";
const http = ({
url = '',
param = {},
type = 'json',
callback = '',
...other
} = {}) => {
wx.showLoading({
title:'请求中...',
})
let timeStart = Date.now();
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + url,
data:param,
header: {
'content-type': type == 'json' ? 'application/json' : 'application/x-www-form-urlencoded',
'token':getToken(),
'openid': getOpenid() || getCouldOpenid().then(openid => openid)
},
...other,
complete: res => {
wx.hideLoading();
console.log(`耗时${Date.now() - timeStart}`);
//重新请求完token,再次执行后的请求在这里拦截
if(callback) { callback(res.data); return }
if(res.statusCode >=200 && res.statusCode < 300) {
/**
* 这是我们自定义的接口状态判断参数
* status_code == 401 为token过期状态需要重新获取token
* status_code == 403 为用户未登陆状态,需要走登录逻辑
*/
if (res.data.status_code == 401 || res.data.status_code == 403) {
if (res.data.status_code == 403) { //用户登陆并获取token
wx.navigateTo({
url: '/pages/loginIn/loginIn',
})
} else if (res.data.status_code == 401) { //token过期
getNewToken(url, param).then(() => {
http({
url,
param,
method: 'post',
callback: resolve
})
})
}
} else {
resolve(res.data)
}
} else {
reject(res);
}
})
})
}
//获取新token
const getNewToken = (url, param) => {
return new Promise((resolve, reject) => {
wx.request({
url: baseUrl + 'user!appLogin.action',
data: {
openid: getOpenid(),
},
header: {
'content-type': 'application/x-www-form-urlencoded'
},
method: 'post',
success: function (res) {
console.log(res);
if (res.data.success) {
wx.setStorageSync('token', res.data.data.token);
wx.setStorageSync('personal', res.data);
resolve(res)
} else {
if (res.data.status_code == 403) {
wx.navigateTo({
url: '/pages/loginIn/loginIn',
})
}
}
},
})
})
}
//获取token
const getToken = () => {
let token = wx.getStorageSync('token') || '';
return token;
}
//获取openid
const getOpenid = () => {
let openid = wx.getStorageSync('openid') || null
return openid;
}
//获取openID
const getCouldOpenid = () => {
return new Promise((resolve, reject) => {
wx.cloud.callFunction({
name: 'login',
data: {},
success: res => {
console.log('[云函数] [login] user openid: ', res.result.openid)
resolve(res.result.openid);
wx.setStorageSync('openid', res.result.openid)
},
fail: err => {
console.error('[云函数] [login] 调用失败', err)
}
})
})
}
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文系转载,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。