封装axios

import axios from 'axios'
import qs from 'qs'
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://47.254.33.68: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)
  }
)
//封装apiAxios 
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,
      data: type === 'POST' || type === 'PUT' ? (config.isStringify ? qs.stringify(config.params) : config.params) : null,
      params: type === 'GET' || type === 'DELETE' ? 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)
        }
      })
      .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),
  delete: option => apiAxios('DELETE', option),
  put: option => apiAxios('PUT', option),
}

  

原文地址:https://www.cnblogs.com/cyf-1314/p/13633224.html