【axios】有木有刷新token的代码参考一下
发布于 6 个月前 作者 vxhly 1606 次浏览 来自 问答

// http response 拦截器
instance.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.message === 'Network Error') Message({ type: 'error', message: 'Network error !!! Try again later !!!' })

    // 如果服务端有响应,显示响应的错误信息
    if (error.response) {
      Message({ type: 'error', message: 'The authentication is invalid. Please login again.' })

      // 退出登录
      switch (error.response.data.status_code) {
        case 401:
          setTimeout(() => {
            store.dispatch('logout')
            router.replace({
              path: '/login',
              query: {
                redirect: router.currentRoute.fullPath
              }
            })
          }, 1000)
          break
        case 404:
          setTimeout(() => {
            store.dispatch('logout')
            router.replace({
              path: '/404',
              query: {
                redirect: router.currentRoute.fullPath
              }
            })
          }, 1000)
          break
        case 500:
          Message({ type: 'error', message: 'The Server is error, try again later !!!' })
      }
    }

    return Promise.reject(error)
  }
)

现在写法是 token 过期退出登录,但是业务需求要能刷新token,不太会写,有木有代码参看一下

2 回复

让他每次在数据请求里面把更新过的token返回给你 你在拦截器里面及时更新就行了

import axios from 'axios'
import store from '@/store'
import router from '@/router'
import config from '@/config'
import { Message } from 'element-ui'

// 创建 axios 实例
const instance = axios.create({
  baseURL: config.serverUrl,
  timeout: 0
})

// http request 拦截器
instance.interceptors.request.use(
  config => {
    if (store.state.auth.authToken) {
      // console.log(store.state.auth.authToken)
      config.headers['Authorization'] = `Bearer ${store.state.auth.authToken}`
    }

    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// http response 拦截器
instance.interceptors.response.use(
  response => {
    let time = setInterval(() => {
      instance.get('/auth/refresh', {
        'headers': {
          'Authorization': `Bearer ${localStorage.authToken}`
        }
      }).then((response) => {
        let authToken = response.headers['authorization'].split(' ')
        let token = authToken[1]
        store.dispatch('refreshToken', token)
        localStorage.authToken = token
      })
    }, 1000 * 600)
    if (store.state.auth.authToken) {
      clearTimeout(time)
    }

    return response
  },
  error => {
    // if (error.message === 'Network Error') Message({ type: 'error', message: 'Network error !!! Try again later !!!' })

    // 如果服务端有响应,显示响应的错误信息
    if (error.response) {
      // Message({ type: 'error', message: 'The authentication is invalid. Please login again.' })

      // 退出登录
      switch (error.response.data.status_code) {
        case 401:
          break
        case 404:
          setTimeout(() => {
            store.dispatch('logout')
            router.replace({
              path: '/404',
              query: {
                redirect: router.currentRoute.fullPath
              }
            })
          }, 1000)
          break
        case 500:
          Message({ type: 'error', message: 'The Server is error, try again later !!!' })
      }
    }

    return Promise.reject(error)
  }
)

export default instance

有观察到token被替换了,但一小时后还是显示token过期,每半小时刷新一次

回到顶部