1. 程式人生 > >vue axios 封裝(二)

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)
  }

}