修改token不刷新问题

master
lemon橪 2021-06-07 11:15:47 +08:00
parent 61273b78b9
commit b80b7205e9
7 changed files with 121 additions and 204 deletions

View File

@ -4,10 +4,8 @@
*/ */
// 开发环境 // 开发环境
const dev = { const dev = {
common: 'http://192.168.0.109:8890', common: "https://common-api.pickmall.cn",
buyer: 'http://192.168.0.109:8888', buyer: "https://buyer-api.pickmall.cn",
seller: 'http://192.168.0.109:8889',
manager: 'http://192.168.0.109:8887'
}; };
// 生产环境 // 生产环境
const prod = { const prod = {

View File

@ -707,12 +707,12 @@
"text": "分类" "text": "分类"
}, },
{ // {
"pagePath": "pages/navigation/point/point-mall", // "pagePath": "pages/navigation/point/point-mall",
"iconPath": "static/tabbar/point-mall.png", // "iconPath": "static/tabbar/point-mall.png",
"selectedIconPath": "static/tabbar/point-mall-s.png", // "selectedIconPath": "static/tabbar/point-mall-s.png",
"text": "积分商城" // "text": "积分商城"
}, // },
{ {
"pagePath": "pages/tabbar/cart/cartList", "pagePath": "pages/tabbar/cart/cartList",
"iconPath": "static/tabbar/cart.png", "iconPath": "static/tabbar/cart.png",

View File

@ -367,6 +367,7 @@ export default {
}, },
}, },
mounted() { mounted() {
const { windowHeight } = uni.getSystemInfoSync(); const { windowHeight } = uni.getSystemInfoSync();
let bottomHeight = 0; let bottomHeight = 0;
let topHeight = 0; let topHeight = 0;

View File

@ -197,13 +197,6 @@ export default {
this.$emit("queryCart"); this.$emit("queryCart");
this.closeMask(); this.closeMask();
} else {
uni.showToast({
title: res.data.message,
duration: 2000,
icon: "none",
});
return false;
} }
}); });
} else { } else {
@ -226,13 +219,7 @@ export default {
)}`, )}`,
}); });
} }
else{
uni.showToast({
title: res.data.message,
duration: 2000,
icon: "none",
});
}
}); });
} }
}, },

View File

@ -7,51 +7,13 @@ Vue.use(Vuex);
const store = new Vuex.Store({ const store = new Vuex.Store({
state: { state: {
verificationKey: "", //获取key表示验证通过 verificationKey: "", //获取key表示验证通过
/**
* 是否需要强制登录
*/
forcedLogin: false,
distributionId:"", //分销员Id 如果当前账户从未登录过时记录 distributionId:"", //分销员Id 如果当前账户从未登录过时记录
hasLogin: storage.getHasLogin(), hasLogin: storage.getHasLogin(),
userInfo: storage.getUserInfo(), userInfo: storage.getUserInfo(),
uuid: storage.getUuid(), uuid: storage.getUuid(),
token: "", token: "",
getHeadInfo: "",
getWeixinHeightInfo: "",
}, },
mutations: { mutations: {
/**
* 获取头部高度 异步使用
* 文档链接在 https://uniapp.dcloud.io/api/system/info?id=getsysteminfosync
* */
GET_HEAD_HEIGHT(state) {
return new Promise((resolve, reject) => {
state.getHeadInfo = uni.getSystemInfoSync();
resolve();
});
},
/**
* 获取微信小胶囊高度 */
MP_WEIXIN_HEIGHT(state) {
// width number 宽度单位px
// height number 高度单位px
// top number 上边界坐标单位px
// right number 右边界坐标单位px
// bottom number 下边界坐标单位px
// left number 左边界坐标单位px
state.getWeixinHeightInfo = uni.getMenuButtonBoundingClientRect();
},
// 前台存储登录状态
SET_HAS_LOGIN(state, val) {
state.hasLogin = val;
},
// 登录信息
SET_USER_INFO(state, val) {
state.userInfo = val;
},
login(state, userInfo) { login(state, userInfo) {
state.userInfo = userInfo || {}; state.userInfo = userInfo || {};
state.userName = state.userName =

View File

@ -1,5 +1,4 @@
import Request from "@/lib/request/index.js"; import Request from "@/lib/request/index.js";
import { configHandle } from "@/utils/tools.js";
import { refreshTokenFn } from "@/api/login.js"; import { refreshTokenFn } from "@/api/login.js";
import storage from "@/utils/storage.js"; import storage from "@/utils/storage.js";
import { md5 } from "@/utils/md5.js"; import { md5 } from "@/utils/md5.js";
@ -84,7 +83,6 @@ function cleanStorage() {
let http = new Request(); let http = new Request();
const refreshToken = getTokenDebounce(); const refreshToken = getTokenDebounce();
const reReqest = new Request();
http.setConfig((config) => { http.setConfig((config) => {
// 没有uuid创建 // 没有uuid创建
@ -141,7 +139,10 @@ http.interceptors.response.use(
// token存在并且token过期 // token存在并且token过期
let token = storage.getAccessToken(); let token = storage.getAccessToken();
if (token && response.statusCode === 403) { if (
(token && response.statusCode === 403) ||
response.data.status === 403
) {
expireToken.includes(token) ? cleanStorage() : ""; expireToken.includes(token) ? cleanStorage() : "";
// jwt token 过期了 // jwt token 过期了
expireToken.push(token); // 把过期token 储存 expireToken.push(token); // 把过期token 储存
@ -150,36 +151,44 @@ http.interceptors.response.use(
// 本地储存的是过期token了重新获取 // 本地储存的是过期token了重新获取
const getTokenResult = await refreshToken(); const getTokenResult = await refreshToken();
if (getTokenResult === "success") { if (getTokenResult === "success") {
// 获取新的token成功 // 获取新的token成功 刷新当前页面
try {
const repeatRes = await reReqest.request( let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
configHandle(response.config) let curRoute = routes[routes.length - 1].route; //获取当前页面路由
); let curParam = routes[routes.length - 1].options; //获取路由参数
response = repeatRes; // 拼接参数
} catch (err) {} let param = "";
for (let key in curParam) {
param += "&" + key + "=" + curParam[key];
}
uni.redirectTo({
url: "/" + curRoute + param.replace("&", "?"),
});
} else { } else {
cleanStorage(); cleanStorage();
} }
} else { } else {
try { cleanStorage();
const repeatRes = await reReqest.request(
configHandle(response.config)
);
response = repeatRes;
} catch (err) {
cleanStorage();
}
} }
// 如果当前返回没登录 // 如果当前返回没登录
} else if (response.statusCode === 403 || response.data.code === 403) { } else if (
(!token && response.statusCode === 403) ||
response.data.code === 403
) {
cleanStorage(); cleanStorage();
// 如果当前状态码为正常但是success为不正常时 // 如果当前状态码为正常但是success为不正常时
} else if (response.statusCode == 200 && !response.data.success || response.statusCode == 400) { } else if (
uni.showToast({ (response.statusCode == 200 && !response.data.success) ||
title: response.data.message , response.statusCode == 400
icon: "none", ) {
duration: 1500, if (response.data.message) {
}); uni.showToast({
title: response.data.message,
icon: "none",
duration: 1500,
});
}
} }
return response; return response;
}, },

View File

@ -1,49 +1,3 @@
import Foundation from '@/utils/Foundation.js';
import {
md5
} from '@/utils/md5.js';
import storage from "@/utils/storage.js";
import store from "@/store/index.js";
// 重新整理一下config
const configHandle = (config) => {
// 'development', 'production'
if (process.env.NODE_ENV === 'development') {
const nonce = Foundation.randomString(6)
const timestamp = parseInt(new Date().getTime() / 1000)
const sign = md5( nonce + timestamp + storage.getAccessToken())
if (config.url.indexOf('?') === -1) {
config.url = `${config.url}?&nonce=${nonce}&timestamp=${timestamp}&sign=${sign}`
} else {
let params = urlParse(config.url);
console.info(params);
let url = config.url.split('?')[0];
params = { ...params,
nonce,
timestamp,
sign
};
let str = '';
for (var k in params) {
console.info(k, params[k])
str += '&' + k + '=' + params[k];
}
str = str.substr(1);
config.url = `${url}?${str}`;
}
config.header = {
...config.header,
uuid: storage.getUuid()
}
} else {
config.header = {
...config.header,
Authorization: storage.getAccessToken(),
uuid: storage.getUuid()
}
}
return config
}
/** /**
* 解析url参数 * 解析url参数
@ -51,59 +5,59 @@ const configHandle = (config) => {
* @return Object {id:12345,a:b} * @return Object {id:12345,a:b}
*/ */
function urlParse(url) { function urlParse(url) {
let obj = {}; let obj = {};
let reg = /[?&][^?&]+=[^?&]+/g; let reg = /[?&][^?&]+=[^?&]+/g;
let arr = url.match(reg); let arr = url.match(reg);
if (arr) { if (arr) {
arr.forEach((item) => { arr.forEach((item) => {
let tempArr = item.substring(1).split('='); let tempArr = item.substring(1).split("=");
let key = decodeURIComponent(tempArr[0]); let key = decodeURIComponent(tempArr[0]);
let val = decodeURIComponent(tempArr.splice(1).join('=')); let val = decodeURIComponent(tempArr.splice(1).join("="));
obj[key] = val; obj[key] = val;
}); });
} }
return obj; return obj;
}; }
const getNetworkType = () => { const getNetworkType = () => {
uni.getNetworkType({ uni.getNetworkType({
success: (res) => { success: (res) => {
if (res.networkType === 'none') { if (res.networkType === "none") {
uni.showToast({ uni.showToast({
title: '网络好像有点问题,请检查后重试!', title: "网络好像有点问题,请检查后重试!",
duration: 2000, duration: 2000,
icon: 'none' icon: "none",
}); });
let pages = getCurrentPages(); let pages = getCurrentPages();
if (pages.length) { if (pages.length) {
let route = pages[pages.length - 1].route; let route = pages[pages.length - 1].route;
if (route !== 'pages/empty/empty') { if (route !== "pages/empty/empty") {
uni.navigateTo({ uni.navigateTo({
url: `/pages/empty/empty?type=wifi` url: `/pages/empty/empty?type=wifi`,
}) });
} }
}else{ } else {
uni.navigateTo({ uni.navigateTo({
url: `/pages/empty/empty?type=wifi` url: `/pages/empty/empty?type=wifi`,
}) });
} }
} }
} },
}) });
} };
const throttle = (fn, that, gapTime) => { const throttle = (fn, that, gapTime) => {
// export function throttle(fn, gapTime) { // export function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) { if (gapTime == null || gapTime == undefined) {
gapTime = 1800 gapTime = 1800;
} }
let _lastTime = that.lastTime let _lastTime = that.lastTime;
let _nowTime = +new Date() let _nowTime = +new Date();
if (_nowTime - _lastTime > gapTime || !_lastTime) { if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(that, arguments) //将this和参数传给原函数 fn.apply(that, arguments); //将this和参数传给原函数
that.lastTime = _nowTime that.lastTime = _nowTime;
} }
} };
/** /**
* 计算传秒数的倒计时 * 计算传秒数的倒计时
@ -111,33 +65,39 @@ const throttle = (fn, that, gapTime) => {
* @returns {{day : *, hours : *, minutes : *, seconds : *}} * @returns {{day : *, hours : *, minutes : *, seconds : *}}
*/ */
const countTimeDown = (seconds) => { const countTimeDown = (seconds) => {
const leftTime = (time) => { const leftTime = (time) => {
if (time < 10) time = '0' + time if (time < 10) time = "0" + time;
return time + '' return time + "";
} };
return { return {
day: leftTime(parseInt(seconds / 60 / 60 / 24, 10)), day: leftTime(parseInt(seconds / 60 / 60 / 24, 10)),
hours: leftTime(parseInt(seconds / 60 / 60 % 24, 10)), hours: leftTime(parseInt((seconds / 60 / 60) % 24, 10)),
minutes: leftTime(parseInt(seconds / 60 % 60, 10)), minutes: leftTime(parseInt((seconds / 60) % 60, 10)),
seconds: leftTime(parseInt(seconds % 60, 10)) seconds: leftTime(parseInt(seconds % 60, 10)),
} };
} };
/** /**
* 计算当前时间到第二天0点的倒计时[] * 计算当前时间到第二天0点的倒计时[]
* @returns {number} * @returns {number}
*/ */
const theNextDayTime = () => { const theNextDayTime = () => {
const nowDate = new Date() const nowDate = new Date();
const time = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate() + 1, 0, 0, 0).getTime() - const time =
nowDate.getTime() new Date(
return parseInt(time / 1000) nowDate.getFullYear(),
} nowDate.getMonth(),
nowDate.getDate() + 1,
0,
0,
0
).getTime() - nowDate.getTime();
return parseInt(time / 1000);
};
export { export {
//configHandle, getNetworkType,
getNetworkType, throttle,
throttle, countTimeDown,
countTimeDown, theNextDayTime,
theNextDayTime };
}