elementUI项目中,只弹一个【token过期提示】信息框的处理

关键代码

javascript 复制代码
let msgArr = document.querySelectorAll('.token401Message')
      if (!msgArr.length) {
        Message({
          customClass: 'token401Message',
          message: response.data.msg,
          type: 'error',
          onClose: () => {
            msgArr = []
          }
        })
      }

完整代码

javascript 复制代码
import axios from 'axios'
import { getToken } from '@/libs/util'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import router from '@/router'
let loadingInstance = null // 记录页面中存在的loading
let loadingCount = 0 // 记录当前正在请求的数量
function showLoading(data) {
  if (loadingCount === 0) {
    loadingInstance = Loading.service({
      lock: true,
      background: 'rgba(255,255,255,.6)',
      text: data || ''
    })
  }
  loadingCount++
}

function hideLoading() {
  let timer = setTimeout(() => {
    loadingCount--
    if (loadingInstance && loadingCount === 0) {
      loadingInstance.close()
      loadingInstance = null
      clearTimeout(timer)
      timer = null
    }
  }, 0)
}
const instance = axios.create({
  // baseURL: baseUrl,
  timeout: 0,
  headers: {
    'Content-Type': 'application/json; charset=utf-8'
  },
  withCredentials: true
})
const no_need_to_refresh_token = [
  '/xxx', // 双因子登录
  '/xxx', // 验证码登录
  '/xxx', // 验证码登录获取验证码
  '/xxx', // 登录接口
  '/xxx', // 获取配置
  '/xxx', // 获取策略
  '/xxx' // 刷新token
]
// 添加请求拦截器
instance.interceptors.request.use(
  async config => {
    if (config.loadingShow) {
      showLoading()
    }
    if (getToken()) {
      config.headers.Authorization = getToken()
      config.headers['Tenant-ID'] = localStorage.getItem('tenantId')
      config.headers['UserId'] = localStorage.getItem('uesrId')
      // 排除双因子 验证码登录 ....
      if (
        no_need_to_refresh_token.every(item => config.url.indexOf(item) === -1)
      ) {
        await store.dispatch('refreshToken')
      }
    }
    return config
  },
  error => {
    if (error.config.loadingShow) {
      hideLoading()
    }
    // 对请求错误做些什么
    return Promise.reject(error)
  }
)

instance.interceptors.response.use(
  async response => {
    if (response.config.loadingShow) {
      hideLoading()
    }
    // token失效
    if (response.data.code === '401 UNAUTHORIZED') {
      router.replace({
        name: 'login',
        params: {
          clear: true
        }
      })
      // 只弹一个【token过期提示】信息框的处理
      let msgArr = document.querySelectorAll('.token401Message')
      if (!msgArr.length) {
        Message({
          customClass: 'token401Message',
          message: response.data.msg,
          type: 'error',
          onClose: () => {
            msgArr = []
          }
        })
      }
      return Promise.reject(new Error(response.data.msg || '请求错误'))
    }
    // 接口报错
    if (
      response.data.code &&
      (response.data.code !== 'SUCCESS' && response.data.code !== 'S1A00000') &&
      response.data.code !== '401 UNAUTHORIZED'
    ) {
      if (!response.request.responseURL.includes('account/verification')) {
        Message({
          message: response.data.msg,
          type: 'error'
        })
        return Promise.reject(new Error(response.data.msg || '请求错误'))
      }
    }
    return response
  },
  async error => {
    if (error.config.loadingShow || error === undefined) {
      hideLoading()
    }
    Message({
      message: error,
      type: 'error'
    })
    // 对响应错误做点什么
    return Promise.reject(error)
  }
)

const http = {
  get: (path, data, config) =>
    instance.get(path, {
      params: data,
      ...config
    }),
  delete: (path, data, config) =>
    instance.delete(path, {
      data: data,
      ...config
    }),
  post: (path, data, config) => instance.post(path, data, config),
  put: (path, data, config) => instance.put(path, data, config)
}

export default http
相关推荐
red润1 分钟前
JavaScript 二维数组初始化:为什么 fill([]) 是个大坑?
前端·javascript·代码规范
一生躺平的仔9 分钟前
Electron 应用时间校准深度探索:从客户端策略到主进程优化
前端
wordbaby9 分钟前
从前端开发者视角解析依赖注入:解耦与可维护性的核心范式
前端
JohnYan9 分钟前
Bun技术评估 - 02 Startup
javascript·后端·bun
玲小珑10 分钟前
Auto.js 入门指南(一)什么是 Auto.js
android·前端
满分观察网友z15 分钟前
揭秘 Intersection Observer:让你的网页“活”起来!
前端·javascript
小佐_小佑16 分钟前
如何用 pnpm patch 给 element-plus 打补丁修复线上 bug(以 2.4.4 修复 PR#15197 为例)
前端
nvvas22 分钟前
前端Nodejs报错:Browserslist: caniuse-lite is outdated. Please run: npx update...
前端
Data_Adventure1 小时前
Vite 项目中使用 vite-plugin-dts 插件的详细指南
前端·vue.js
八戒社1 小时前
如何使用插件和子主题添加WordPress自定义CSS(附:常见错误)
前端·css·tensorflow·wordpress