大致流程:
1、用户登录之后会返回两个token(access_token,refresh_token),请求数据时,请求头为access_token;
2、当返回值为code=103时(access_token过期时),通过接口(刷新token)api向后端获取新的access_token,请求参数为refresh_token;
3、拿到新的token(access_token,refresh_token)之后替换掉之前的token,重新请求数据接口;
4、如果请求(刷新token)api也过期,则跳到登录页
1、封装wx.request
在http文件夹下创建request.js
代码如下:
// 网络请求
// 获取数据
//获取数据状态:loading、toast
// 请求头处理(机型、大小、系统、屏幕)
let store = require("../utils/store.js")
let system = store.getSystemInfo()
const clienInfo = {
"clientType": "mp",
"appnm": "myApplet",
"model": system.model,
"os": system.system,
"screen": system.screenWidth + "*" + system.screenHeight,
"version": App.version,
"chennel": "miniprogram"
}
module.exports = {
fetch: (url, data = {}, option = {}) => {
let { loading = true, toast = true, method = 'get' } = option
return new Promise((resolve, reject) => {
if (loading) {
wx.showLoading({
title: '努力加载中...',
mask: true
})
}
let env = App.config.baseApi;
wx.request({
url: env + url,
data,
method,
header: {
"clienInfo": JSON.stringify(clienInfo),
"AUTHORIZATION": store.getItem("accescc_token")
},
success: function(result) {
let res = result.data
if (res.code == 200 || res.code == 10000) {
if (loading) {
wx.hideLoading();
}
resolve(res);
} else if (res.code == 103) {
wx.request({
url: env + "/index/Customer/refresh",
method: 'POST',
header: {
"clienInfo": JSON.stringify(clienInfo),
"AUTHORIZATION": store.getItem("refresh_token")
},
success: function(result) {
console.log('result', result.data.code)
if (result.data.code == 200) {
wx.setStorageSync('accescc_token', result.data.data)
wx.startPullDownRefresh()
resolve(res)
} else if (result.data.code == 103) {
wx.showToast({
title: 'token失效,重新登录',
icon: "none"
})
setTimeout(() => {
wx.redirectTo({
url: '/paegs/login/login',
})
}, 2000)
} else {
wx.showToast({
title: result.msg,
icon: "none"
})
}
}
})
} else {
if (toast) {
wx.showToast({
mask: true,
title: res.msg,
icon: 'none',
duration: 2000
})
} else {
wx.hideLoading();
}
resolve(res);
}
},
fail: function(result) {
}
})
})
},
}
ps:使用wx.startPullDownRefresh(),需要在app.json配置"enablePullDownRefresh": true
2、在请求接口的页面监听用户下拉动作
onPullDownRefresh: function () {
this.getList()//请求数据方法
},
emmm,大概实现方法是这样想的了,如果有人有更好的实现方式,欢迎一起讨论(嘻嘻)