直接上代码!
1、首先在 uview-ui/libs/request/index.js 文件下,新增红框内的代码
Object.assign(response.data, { options })
2、修改 http.interceptor.js(http拦截器)文件
// @/utils/wxApplet/common.js 下的获取token的请求也贴在这里了
const appletAuthTest = () => {
return new Promise((resolve, reject) => {
Vue.prototype.$u.api.appletAuthTest().then(res => {
Vue.prototype.$u.vuex('vuex_token', res.access_token);
resolve()
});
})
}
export default {
appletAuthTest
}
import config from '@/config.js'
import common from '@/utils/wxApplet/common.js'
/**
* http拦截器
*/
const install = (Vue, vm) => {
// 自定义配置参数
Vue.prototype.$u.http.setConfig({
// baseUrl: config.HTTP_REQUEST_URL,
loadingText: '努力加载中~',
loadingTime: 800,
// 是否在拦截器中返回服务端的原始数据
originalData: true
// ......
});
// 是否正在刷新的标记
let isRefreshing = false
// 重试队列,每一项将是一个待执行的函数形式
let requests = []
// 请求拦截
Vue.prototype.$u.http.interceptor.request = async (configs) => {
// 租户id
configs.header['TENANT-ID'] = '1';
if (vm.$store.state.vuex_openid) {
configs.header['openId'] = vm.$store.state.vuex_openid;
}
// 绕过获取token 或 刷新token的接口
if (configs.url.indexOf('/admin/user/ysfauth') >= 0 || configs.url.indexOf('/admin/user/ysfauth2') >= 0) {
return configs
}
let vuex_token = vm.$store.state.vuex_token;
if (vuex_token) {
configs.header[config.TOKEN_NAME] = `Bearer ${vuex_token}`;
}
return configs;
}
// 响应拦截
Vue.prototype.$u.http.interceptor.response = async (res) => {
// 用户凭证已过期
if (res.statusCode === 401) {
if (!isRefreshing) {
isRefreshing = true
// 重新登录 刷新token
await common.appletAuthTest()
// 如果使用:Promise.all(requests),我这边实际上并不会逐个按请求队列顺序重新发起请求(只会重发第一个请求)
// 所以改用:requests.forEach
requests.forEach(cb => cb())
// 清空请求队列
requests = []
isRefreshing = false;
return vm.$u.http.request(res.data.options)
} else {
// 同时并发出现的请求 新的token没回来之前 先用promise 存入等待队列中,等token刷新后直接执行
return new Promise((resolve) => {
requests.push(() => {
resolve(vm.$u.http.request(res.data.options))
})
})
}
} else if (res.statusCode === 200) {
if (res.data.code == 0) {
return res.data.data;
} else {
// 如果返回false,则会调用Promise的reject回调
if (res.data.msg) {
vm.$u.toast(res.data.msg)
} else {
vm.$u.toast(res.errMsg)
}
return false;
}
} else {
vm.$u.toast(res.data.msg);
return false;
}
}
}
export default {
install
}
可以根据自己的业务情况去修改,希望对你们有帮助哈!
参考文章:前端 - 使用uniapp+uview ui框架封装的Http请求,怎么做无痛刷新token? - SegmentFault 思否