美文网首页
token失效重新请求token后请求接口

token失效重新请求token后请求接口

作者: 糖醋里脊120625 | 来源:发表于2021-12-17 14:30 被阅读0次
    import externalaxios from 'axios';
    import { externalApi } from '@/common/js/api';
    import {Message} from 'element-ui';
    // externalaxios.defaults.timeout = 30000;
    // externalaxios.defaults.baseURL = '';
    
    
    // ****************************************************************************************
    
    function getLocalToken () {
      const token = window.sessionStorage.getItem('externalLogintoken')
      return token
    }
    
    
    // ****************************************************************************************over
    
    const service = externalaxios.create({
      baseURL: '',
      headers: {
        'Content-Type': 'application/json',
        'token': getLocalToken() // headers塞token
      },
    })
    
    service.setToken = (token) => {
      service.defaults.headers['token'] = token
      window.sessionStorage.setItem('externalLogintoken', token)
    }
    
    
    //http request 拦截器
    service.interceptors.request.use( config => {
        
        if(sessionStorage.getItem("externalLogintoken")){
          var token = sessionStorage.getItem("externalLogintoken");
        }else{
          var token = null;
        }
        
        // config.data = JSON.stringify(config.data);
        config.headers = Object.assign({
          'Content-Type': 'application/json;charset=UTF-8',
          'token': token,
        }, config.headers);
        return config;
      },
      error => {
        return Promise.reject(err);
      }
    );
    
    
    //http response 拦截器
    // 是否正在刷新的标记
    let isRefreshing = false
    // 重试队列,每一项将是一个待执行的函数形式
    let requests = []
    
    service.interceptors.response.use(response => {
      const { code } = response.data
    
      if (code == 401) {
        sessionStorage.removeItem("externalLogintoken");
        const config = response.config
        if (!isRefreshing) {
          isRefreshing = true
          return refreshToken().then(res => {
            service.setToken(res.token)
            const { token } = res.token
            config.headers['token'] = res.token
            window.sessionStorage.setItem('externalLogintoken', res.token)
            config.baseURL = ''
            // 已经刷新了token,将所有队列中的请求进行重试
            requests.forEach(cb => cb(token))
            requests = []
            return service(config)
          }).catch(res => {
            console.error('refreshtoken error =>', res)
            //window.location.href = '/'
          }).finally(() => {
            isRefreshing = false
          })
        }
        else {
          // 正在刷新token,将返回一个未执行resolve的promise
          return new Promise((resolve) => {
            // 将resolve放进队列,用一个函数形式来保存,等token刷新后直接执行
            requests.push((token) => {
              config.baseURL = ''
              config.headers['token'] = sessionStorage.getItem("externalLogintoken")
              resolve(service(config))
            })
          })
        }
      } else if (code == 70101) {
        // token 获取失败
        Message({
          message: "授权失败,请稍后重试",
          type: "error",
          duration: 5 * 1000
        });
        requests = []
      }
    
      return response;
    },
      error => {
        return Promise.reject(error)
      }
    )
    export default service;
    
    
    /**
     * 封装get方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    export function externalget(url, params = {}) {
      return new Promise((resolve, reject) => {
        service.get(url, {params: params})
          .then(response => {
            if(response){
              resolve(response.data);
            }else{
              resolve(null);
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    }
    
    export function getExal(url, params = {}) {
      return new Promise((resolve, reject) => {
        service.get(url,{
          responseType: "blob"
        })
          .then(response => {
            if(response){
              resolve(response);
            }else{
              resolve(null);
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    }
    
    
    export function externalpost(url, data = {}) {
      return new Promise((resolve, reject) => {
        service.post(url, data)
          .then(response => {
            if(response){
              resolve(response.data);
            }else{
              resolve(null);
            }
            
          }, err => {
    
            reject(err)
          })
      })
    }
    
    export function externalput(url, data = {}) {
      return new Promise((resolve, reject) => {
        service.put(url, data)
          .then(response => {
            resolve(response.data);
          }, err => {
            reject(err)
          })
      })
    }
    
    
    /**
     * 封装patch请求
     * @param url
     * @param data
     * @returns {Promise}
     */
    
    export function patch(url, data = {}) {
      return new Promise((resolve, reject) => {
        externalaxios.patch(url, data)
          .then(response => {
            resolve(response.data);
          }, err => {
            reject(err)
          })
      })
    }
    
    /**
     * 封装put请求
     * @param url
     * @param data
     * @returns {Promise}
     */
    
    export function put(url, data = {}) {
      return new Promise((resolve, reject) => {
        externalaxios.put(url, data)
          .then(response => {
            resolve(response.data);
          }, err => {
            reject(err)
          })
      })
    }
    
    /**
     * 封装delete方法
     * @param url
     * @param data
     * @returns {Promise}
     */
    export function deletes(url, params = {}) {
      return new Promise((resolve, reject) => {
        externalaxios.delete(url, {
          params: params
        })
          .then(response => {
            resolve(response.data);
          })
          .catch(err => {
            reject(err)
          })
      })
    }
    
    
    
    
    function refreshToken (){
      return  externalApi.externalToken().then(res => res.data)
    }
    
    
    

    相关文章

      网友评论

          本文标题:token失效重新请求token后请求接口

          本文链接:https://www.haomeiwen.com/subject/rinefrtx.html