Axios发起请求,并拦截刷新TOKEN,结合教程里面的Api实战写的。刷新TOKEN会有重复的问题

因为我在页面中模拟了三次请求,所以TOKEN失效后会有三次重复,也就这个缺点了

目前还有一个缺点,就是如果一个页面有三个请求,然后刚才TOKEN过期,会重复三个请求

import axios from 'axios'
import { ElLoading, ElMessage } from 'element-plus'
import dayjs from 'dayjs';

const service = axios.create({
    baseURL: "http://localhost:8080/api/v1",
    timeout:5000,
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    }
})

const http = axios.create({
    baseURL: "http://localhost:8080/api/v1",
    timeout:5000,
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    }
})

// 用于刷新TOKE的请求拦截器
http.interceptors.request.use(config => {
    if(localStorage.getItem('token')) {
        config.headers.Authorization = "Bearer " + localStorage.getItem('token') || ''
    }
    return config
})

// 请求拦截
service.interceptors.request.use(config => {

    // token已经过期
    if(localStorage.getItem("expires_in") && localStorage.getItem("token") && localStorage.getItem("expires_in") < dayjs().unix()) {
        return new Promise(function(resolve, reject) {
            http({
                url: "authorizations/current",
                method: "put",
            }).then(response => {
                localStorage.setItem("token", response.data.access_token)
                localStorage.setItem("expires_in", dayjs().add(response.data.expires_in, 'second').unix())

                config.headers.Authorization = "Bearer " + response.data.access_token
                resolve(config)
            })
        })
    }else {
        if(localStorage.getItem('token')) {
            config.headers.Authorization = "Bearer " + localStorage.getItem('token') || ''
        }
        return config
    }
})

// 响应拦截
service.interceptors.response.use(response => {
    const code = response.data.code
    return response
})

export default service

我实在想不到办法,有高手帮忙一下

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 2

接口放到 axios.all 里面发送

2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!