1. 程式人生 > 實用技巧 >封裝axios

封裝axios

import axios from 'axios'
import qs from 'qs'
//import configer from '@/config/index.js'
import { MessageBox } from 'element-ui'
import toast from '@/components/toast/toast.js'
import router from '@/router'
import utils from '@/utils/utils'
axios.defaults.baseURL = 'http://172.31.241.107:6081' //介面地址
// 自定義判斷元素型別JS
function toType (obj) {
  return Object.prototype.toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 引數過濾函式
function filterNull (o) {
  for (var key in o) {
    if (o[key] === null) {
      delete o[key]
    }
    if (toType(o[key]) === 'string') {
      o[key] = o[key].trim()
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}

axios.interceptors.request.use(
  config => {
    if (utils.getCookie('manage_manageToken')) { //登陸成功返回的tooken
      config.headers['X-Access-Token'] = utils.getCookie('manage_manageToken')
      config.headers['If-Modified-Since'] = 0
    }else{
      config.headers['X-Access-Token'] = ''
      config.headers['If-Modified-Since'] = 0
    }
    return config
  },
  error => {
    toast({
      message: '抱歉,系統出錯了!',
      type: 'warning'
    })
    return Promise.reject(error)
  }
)

function apiAxios (type, option) {
  let config = {
    url: '',
    params: null,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    isStringify: false,
    isTrim: true
  }
  config = Object.assign({}, config, option)
  if (config.params && config.isTrim) {
    config.params = filterNull(config.params)
  }
  return new Promise((resolve, reject) => {
    let timeType = config.url.indexOf('?') === -1 ? '?_t=' : '&_t='
    let time = timeType + new Date().getTime()
    axios({
      method: type,
      url:config.url + time,
      data: type === 'POST' ? (config.isStringify ? qs.stringify(config.params) : config.params) : null,
      params: type === 'GET' ? config.params : null,
      headers: config.headers,
      responseType: config.responseType || 'json'
    })
      .then(res => {
        if (res.data && res.data.code === '0') {
          resolve(res.data)
        } else if (res.data && (res.data.code === '-1' || res.data.code === '-100' || res.data.code === '-200')) {
          toast({
            message: res.data.message,
            type: 'warning'
          })
        } else if (res.data && res.data.code === '-2') {
        
        } else if (res.data && res.data.code === '-3') {
        
        } else if (res.data && res.data.code === 'OMR100011') {
         
        } else {
          resolve(res.data)
        }
        //secrityPrefix = utils.getCookie('manage_manageToken') ? '/user' : ''
      })
      .catch(err => {
        if (err) {
          if (err && err.response.status === 404) {
            const alerter = document.querySelector('.el-message-box__content')
            if (alerter && alerter.textContent === '登陸失效,請重新登陸') return
            MessageBox.alert('登陸失效,請重新登陸', '溫馨提示', {
              confirmButtonText: '確定',
              callback: action => {
                utils.clearAllCookie()
                router.replace({path: '/login'})
              }
            })
          } else {
            toast({
              message: '抱歉,系統出錯了!',
              type: 'warning'
            })
          }
          reject(err)
        }
       
      })
  })
}

// 返回在vue模板中的呼叫介面
export default {
  get: option => apiAxios('GET', option),
  post: option => apiAxios('POST', option)
}