这篇文章次要想记录之前遇到的jwt过期,前端封装申请解决jwt过期的问题。
// 文件request.js中对立封装申请import {AxiosStatus} from 'axios-status';import axios from 'axios';import utils from '../util';// 被挂起的申请数组let refreshSubscribers = [];// 是否有申请正在刷新tokenwindow.isRefreshing = false;const axiosStatus = new AxiosStatus({ timeout: 20, // default 10 autoRetry: false // default false});axiosStatus.register(axios);function resendCatchedRequest () { const list = refreshSubscribers; refreshSubscribers = []; window.isRefreshing = false; if (!list || !list.length) { return } list.forEach((item) => { postRequest(item.url, item.opts).then((...args) => { item.resolveHandler && item.resolveHandler(...args) }) .catch((...args) => { item.rejectHandler && item.rejectHandler(...args) }) })}async function postRequest (url, opts = {}) { let jwt = await utils.freshJWT(); // 获取jwt if (!opts['headers']) { opts['headers'] = {} } opts['headers']['Content-Type'] = 'application/json'; opts['headers']['jwt'] = jwt; return axiosStatus.request({ url: url, method: opts['method'] || 'get', baseURL: opts['baseURL'], headers: opts['headers'], params: opts['params'], data: opts['data'], timeout: 10000, withCredentials: false, cancelToken: opts['cancelToken'], success: (res) => { if (res.status !== 200) { return { code: res.status, msg: res.statusText } } // 服务端告知jwt过期 if (res.data.code == 1004) { return new Promise((resolve, reject) => { refreshSubscribers.push({ url: url, opts: opts, resolveHandler: resolve, rejectHandler: reject, }); window.isRefreshing = true; // 从某个办法中回去最新的jwt的值 笼罩原来localStorage 中的值 API.login().then(data => { window.localStorage.setItem('jwt', data.jwt); resendCatchedRequest(); }) }) } return res.data }, error: () => { // console.log('in error', error) } })}export default { postRequest,}