Skip to content

token 过期处理

javascript
// store/modules/user.js
const actions = {
	async userLogin({ commit }, userinfo) {  // 获取token
		try {
			const res = await uni.$u.api.login(userinfo)
			uni.setStorageSync('IntToken', res.token)
			uni.setStorageSync('LoginTime', new Date().getTime());  // 设置登录时间
			uni.setStorageSync("validNearTime", 25 * 60000) // 设置登录过期临界时间
      uni.reLaunch({
				url: "/pages/tabbar/home",
			});
		} catch (err) {
			throw new Error(err)
		}
	},
}

// 响应拦截
	Vue.prototype.$u.http.interceptor.response = (res) => {
		if (vm.$db.get("IntToken")) {
			/**
			 * token 过期处理
			 * 后端默认过期时间为30分钟
			 * 登录时长大于临界时间25分钟替换token
			 */
			let time = new Date().getTime() - Number(vm.$db.get("LoginTime"))
			if (time > Number(vm.$db.get("validNearTime"))) {
				vm.$db.set('IntToken', res.token)
			}
		};
		// token 失效处理
		if (res.code == 49200) {
			vm.$store.dispatch("user/userLogout")
		};
		return res
	}
}
/* 请求之后拦截器 */
	shoproRequest.interceptor.response(async (response, options) => {
		uni.hideLoading();
		if (response.code == 49200) {
			// 无痛刷新
			return response = await doRequest(options)

		} else if (response.code != 49000) {
			if (toastAfter) {
				uni.showToast({
					title: response.msg || '请求出错,稍后重试',
					icon: 'none',
					duration: 1000,
					mask: true
				});
			}
			// throw (response.msg || '请求出错,稍后重试');
			return Promise.reject(response.msg || '请求出错,稍后重试')
		} else {
			return response.result || response.msg
		}


		// token过期注销
		// if (response.code === 401) {
		// 	store.dispatch('logout');
		// 	store.dispatch('showAuthModal');
		// 	throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
		// }

		// return response
	})

	return shoproRequest.request({
		url: api.url,
		data,
		method: api.method,
		header: api.header
	})

}


async function doRequest(config) {
	const { token, appId } = await http("home.getToken", {
		hash: uni.getStorageSync('hash'),
	})
	uni.setStorageSync("token", token);
	uni.setStorageSync("appId", appId);
	for (const key in apiList) {
		for (const i in apiList[key]) {
			if (apiList[key][i].header.path == config.header.path) {
				const resold = await http(`${key}.${i}`, {
					...config.data,
				})
				return resold
			};
		}
	}
}

基于 MIT 许可发布