关于javascript:vue-axios封装请求-刷新过期JWT

48次阅读

共计 1568 个字符,预计需要花费 4 分钟才能阅读完成。

这篇文章次要想记录之前遇到的 jwt 过期, 前端封装申请解决 jwt 过期的问题。

// 文件 request.js 中对立封装申请
import {AxiosStatus} from 'axios-status';
import axios from 'axios';
import utils from '../util';
// 被挂起的申请数组
let refreshSubscribers = [];
// 是否有申请正在刷新 token
window.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,}

正文完
 0