调整 token过期 及 重定向首页问题
This commit is contained in:
+59
-3
@@ -2,23 +2,79 @@
|
||||
// const baseUrl = "https://api.collect.xyh.muzili.top/"; //这里放置url域名32044
|
||||
const baseUrl = "https://bsh.info.yw.hnzhwlkj.cn/"; //这里放置url域名32044
|
||||
// const baseUrl = "https://114.215.24.240:8106/api/v1/"; //这里放置url域名32044
|
||||
import { loginOnce } from '@/utils/auth.js';
|
||||
|
||||
// 正在重试的请求队列
|
||||
const retryQueue = [];
|
||||
let isRefreshing = false;
|
||||
|
||||
/**
|
||||
* 处理 401 错误,重新登录后重试请求
|
||||
*/
|
||||
async function handle401Error(originalOptions) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// 将请求加入队列
|
||||
retryQueue.push({ options: originalOptions, resolve, reject });
|
||||
|
||||
// 如果没有正在刷新 token,开始刷新
|
||||
if (!isRefreshing) {
|
||||
isRefreshing = true;
|
||||
|
||||
loginOnce().then((result) => {
|
||||
isRefreshing = false;
|
||||
|
||||
if (result.success) {
|
||||
// 登录成功,重试所有队列中的请求
|
||||
retryQueue.forEach(({ options, resolve, reject }) => {
|
||||
request(options).then(resolve).catch(reject);
|
||||
});
|
||||
// 清空队列
|
||||
retryQueue.length = 0;
|
||||
} else {
|
||||
// 登录失败,拒绝所有队列中的请求
|
||||
retryQueue.forEach(({ reject }) => {
|
||||
reject({ data: { message: '登录失败,请重新登录' } });
|
||||
});
|
||||
retryQueue.length = 0;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function request(options){//封装的requset
|
||||
let { url,data,method } = options;
|
||||
data = data || {},
|
||||
uni.showLoading({
|
||||
title: ''
|
||||
});
|
||||
|
||||
|
||||
return new Promise((resolve,rejext)=>{
|
||||
uni.request({//这里是uniapp网络请求的api
|
||||
url: baseUrl + url, //仅为示例,并非真实接口地址。
|
||||
data,
|
||||
header:{'content-type': 'application/x-www-form-urlencoded','Fdesk-Auth-Token': 'Bearer ' + uni.getStorageSync('token'),'Fdesk-Language': uni.getStorageSync('i18locale')?uni.getStorageSync('i18locale'):'zh','Fdesk-Login-Type': 'wechat','Fdesk-System-Code':'wechat'},
|
||||
method:method||"GET",//默认请求方式是get
|
||||
success: (res) => {
|
||||
success: async (res) => {
|
||||
uni.hideLoading();
|
||||
resolve(res)
|
||||
|
||||
// 检查 401 错误(可能是 res.statusCode === 401 或 res.data.code === 401)
|
||||
if (res.statusCode === 401 || (res.data && res.data.code === 401)) {
|
||||
console.log('Token expired, attempting silent login...');
|
||||
try {
|
||||
const retryResult = await handle401Error(options);
|
||||
resolve(retryResult);
|
||||
} catch (error) {
|
||||
resolve(res); // 返回原始错误响应
|
||||
}
|
||||
} else {
|
||||
resolve(res);
|
||||
}
|
||||
},
|
||||
fail: (err) => {
|
||||
uni.hideLoading();
|
||||
rejext(err);
|
||||
},
|
||||
complete: (data)=>{
|
||||
uni.hideLoading();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user