vue axios封装请求 + 刷新过期JWT

这篇文章主要想记录之前遇到的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,
}

评论

暂无评论