• vue axios 封装(二)


    封装二:

    http.js

    import axios from 'axios'
    import storeHelper from './localstorageHelper'
    // 全局设置
    const obj = storeHelper.getStorageObject()
    if (obj && obj.tokenInfo) {
      // console.info("http.js", obj);
      axios.defaults.headers.common['Authorization'] = 'bearer ' + obj.tokenInfo.access_token
    }
    const apiRoot = process.env.BASE_API_OF_SYS_MANAGE // 配置API路径
    axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
    axios.defaults.baseURL = apiRoot
    
    // 设置请求的次数
    axios.defaults.retry = 2
    // 设置请求的间隙(ms)
    axios.defaults.retryDelay = 1000
    
    // 拦截响应response,并做一些错误处理
    axios.interceptors.response.use(function(response) {
      // 对响应数据的全局状态码处理
      const json = response.data
      if (json.state !== '1') {
        switch (json.state) {
          case '2':
            break
          case '3':
            break
          case '4':
            break
          case '5':
            break
          default:
            break
        }
        // this.$Message.warning(json.msg !== "" ? json.msg : json.state);
      }
      return response
    }, function axiosRetryInterceptor(err) {
      if (err && err.response) {
        switch (err.response.status) {
          case 400:
            err.message = '请求错误'
            break
          case 401:
            err.message = '未授权,请登录'
            break
          case 403:
            err.message = '拒绝访问'
            break
          case 404:
            err.message = `请求地址出错: ${err.response.config.url}`
            break
          case 408:
            err.message = '请求超时'
            break
          case 500:
            err.message = '服务器内部错误'
            break
          case 501:
            err.message = '服务未实现'
            break
          case 502:
            err.message = '网关错误'
            break
          case 503:
            err.message = '服务不可用'
            break
          case 504:
            err.message = '网关超时'
            break
          case 505:
            err.message = 'HTTP版本不受支持'
            break
          default:
        }
        if (err.response.status === 401) {
          var config = err.config
          // If config does not exist or the retry option is not set, reject
          if (!config || !config.retry) return Promise.reject(err)
          // Set the variable for keeping track of the retry count
          config.__retryCount = config.__retryCount || 0
          // Check if we've maxed out the total number of retries
          if (config.__retryCount >= config.retry) {
            // Reject with the error
            return Promise.reject(err)
          }
          // Increase the retry count
          config.__retryCount += 1
    
          // Create new promise to handle exponential backoff
          var backoff = new Promise(function(resolve) {
            /* setTimeout(function () {
                        resolve();
                    }, config.retryDelay || 1); */
            // 利用刷新Token代替间隔周期
            getToken(function(token) {
              if (token.access_token) {
                config.headers.Authorization = 'bearer ' + token.access_token;
              }
              resolve()
            })
          })
          // Return the promise in which recalls axios to retry the request
          return backoff.then(function() {
            return axios(config) // 返回的请求若正常还回到最初请求的响应
            // .then(function (response) {
            //     if (this.debug) console.log(response.data);
            //     if (this.debug) console.log(response.status);
            //     if (this.debug) console.log(response.statusText);
            //     if (this.debug) console.log(response.headers);
            //     if (this.debug) console.log(response.config);
            //     return Promise.resolve();
            // });
            // 开启另一请求,则会关闭当前拦截效果
            /* return getToken(function (token) {
                        if (token.access_token) {
                            config.headers.Authorization = "bearer " + token.access_token;
                        }
                        return axios(config)
    
                    }); */
          })
        }
      }
      return Promise.reject(err)
    })
    /**
     * 请求Token
     * @param {*} callback 请求成功回调
     * @param {*} user token请求参数,登录信息
     */
    function getToken(callback, user) {
      var srcwin = window.opener || window.parent
      srcwin.postMessage('SUBSYS.ADMIN|GetToken', '*')
    
      setTimeout(function() {
        if (callback) {
          const obj = storeHelper.getStorageObject()
          // console.log('wandan')
          // console.log(obj)
          if (obj && obj.tokenInfo) {
            axios.defaults.headers.common['Authorization'] = 'bearer ' + obj.tokenInfo.access_token
            return callback(obj.tokenInfo)
          }
        }
      }, 2000)
      return
      // ---------------------
    }
    axios.install = (Vue) => {
      Vue.prototype.$http = axios
      Vue.prototype.$getToken = getToken
      Vue.prototype.$mystore = storeHelper
    }
    
    /**
     * 封装post请求
     * @param url
     * @param data
     */
    export function post(url, data = {}) {
      return new Promise((resolve, reject) => {
        axios.post(url, data)
          .then(response => {
            resolve(response)
          }, err => {
            reject(err)
          })
      })
    }
    
    /**
     * 封装get请求
     * @param url
     * @param data
     */
    export function get(url, data) {
      url += '?'
      var objKeys = Object.keys(data)
      for (var i = 0; i < objKeys.length; i++) {
        if (i < objKeys.length - 1) {
          url = url + objKeys[i] + '=' + data[objKeys[i]] + '&'
        } else {
          url = url + objKeys[i] + '=' + data[objKeys[i]]
        }
      }
      return new Promise((resolve, reject) => {
        axios.get(url)
          .then(response => {
            resolve(response)
          }, err => {
            reject(err)
          })
      })
    }
    
    /**
     * 封装delete请求
     * @param url
     * @param data
     */
    export function del(url, data) {
      return new Promise((resolve, reject) => {
        axios.delete(url, data)
          .then(response => {
            resolve(response)
          }, err => {
            reject(err)
          })
      })
    }
    
    /**
     * 封装put请求
     * @param url
     * @param data
     */
    export function put(url, data) {
      return new Promise((resolve, reject) => {
        axios.put(url, data)
          .then(response => {
            resolve(response)
          }, err => {
            reject(err)
          })
      })
    }
    

    localstorageHelper.js

    const key = 'Admin-Token'
    
    import {
      getToken,
      setToken,
      removeToken
    } from '@/utils/auth' // 验权
    
    function setStorageObject(_data) {
      // 存储,IE6~7 cookie 其他浏览器HTML5本地存储
      if (window.localStorage) {
        localStorage.setItem(key, JSON.stringify(_data))
        // console.log('设置本地token')
        setToken(_data.tokenInfo.access_token)
      } else {
        setToken(_data.tokenInfo.access_token)
      }
    }
    
    export default {
      /* data() {
          return this.data;
      } */
      // key: "CMP.WEB.DATA",
      /** 当前用户信息的全部存储对象 */
      data: {
        userInfo: {
          id: 0,
          username: '',
          openId: '',
          authInfo: {
            links: [],
            permissionInfo: {}
          }
        },
        tokenInfo: {
          access_token: '',
          expires_in: '2018-04-28T20:40:47.784363+08:00',
          token_type: 'Bearer'
        }
      },
      /**
       * 获取全部存储对象
       */
      getStorageObject() {
        const _data = window.localStorage ? localStorage.getItem(key) : getToken(key)
        if (_data) {
          this.data = JSON.parse(_data)
        } else {
          this.data = {}
        }
        // this.data = _data
        return this.data
      },
      /** 是否登录状态 */
      isLogin() {
        this.getStorageObject()
        if (!this.data || !this.data.userInfo || !this.data.userInfo.username) {
          return false
        } else {
          return true
        }
      },
      /** 是否注销状态 */
      isLogout() {
        this.getStorageObject()
        if (this.data.userInfo) {
          return false
        } else {
          return true
        }
      },
      /** 删除当前用户存储对象,用于注销 */
      removeStorageObject() {
        // 存储,IE6~7 cookie 其他浏览器HTML5本地存储
        if (window.localStorage) {
          window.localStorage.removeItem(key)
        } else {
          removeToken(key)
        }
      },
      /**
       * 设置token信息对象,需要先获取data.tokenInfo,再修改data.tokenInfo,最后再通过此方法更新
       * @param {JSON} _data tokenInfo
       */
      setTokenInfo(_data) {
        this.data.tokenInfo = _data
        setStorageObject(this.data)
      },
      /**
       * 设置用户信息对象,需要先获取data.userInfo,再修改data.userInfo,最后再通过此方法更新
       * @param {JSON} _data userInfo
       */
      setUserInfo(_data) {
        this.data.userInfo = _data
        setStorageObject(this.data)
      },
      /**
       * 设置用户信息对象,需要先获取data.userInfo,再修改data.userInfo,最后再通过此方法更新
       * @param {JSON} _data userInfo
       */
      setAllInfo(_data) {
        this.data = _data
        setStorageObject(this.data)
      }
    
    }
    
  • 相关阅读:
    IOS 两种控制器的使用,纯代码UITabBarController 与 UINavigationController
    iOS UI控件总结(全)
    IOS 参数string 转成url
    CocoaPods 的使用与一些异常情况的处理
    创建自己的 FrameWork(含demo)-Xcode7环境
    UITextView 一些属性的设置
    跳转第二弹
    iOS--登录注册页面-趣享-接口设计
    《大道至简》第一章阅读笔记
    软件工程个人作业02
  • 原文地址:https://www.cnblogs.com/cc-freiheit/p/9933606.html
Copyright © 2020-2023  润新知