封裝axios請求

行走的羊駝駝發表於2018-12-15
import { Message} from 'element-ui' //引入element彈窗組建
import loginInfo from '../store/loginInfo.js'
import router from '../router'//引入路由
var root = 'http://app.senpuyun.com/' // 配置API介面地址
var axios = require('axios') // 引用axios
// 自定義判斷元素型別JS
function toType(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}
// 引數過濾函式
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null || o[key] === '' ) {
      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
function apiAxios(method, url, params, success, failure) {
  if (params) {
    params = filterNull(params)
  }
  axios({
      method: method,
      url: url,
      data: method === 'POST' || method === 'PUT' ? params : null,
      params: method === 'GET' || method === 'DELETE' ? params : null,
      baseURL: root,
      withCredentials: true //開啟cookies
    })
    .then(function (res) {
      if (res.data.status === 1000 || res.data.status === 1005 || res.data.status === 1010) {
        if (success) {
          if (Array.isArray(res.data.data) && res.data.data.length === 0) {//後臺資料不規範,所以加了這個
            res.data.data.list = []
          }
          success(res.data)
        }
      } else {
        if (failure) {
          Message.error(res.data.msg)
          failure(res.data)
        } else if (res.data.status === 1016) {
          Message.error('登入失效,請重新登入!')
          loginInfo.setIslogin(false)
          router.push('/login')
        } else {
          Message.error(res.data.msg)
        }
      }
    })
    .catch(function (err) {
      if (err) {
        err = String(err)
        if (err.includes('Network Error')) {
          Message.error('請檢查網路,網路端出錯了哦')
        } else if (err.includes('TypeError: Cannot read property')) {
          return false
        } else {
          Message.error('服務端出錯了哦')
        }
      }
    })
}

// 返回在vue模板中的呼叫介面
export default {
  get: function (url, params, success, failure) {
    return apiAxios('GET', url, params, success, failure)
  },
  post: function (url, params, success, failure) {
    return apiAxios('POST', url, params, success, failure)
  },
  put: function (url, params, success, failure) {
    return apiAxios('PUT', url, params, success, failure)
  },
  delete: function (url, params, success, failure) {
    return apiAxios('DELETE', url, params, success, failure)
  },
  root: root
}
複製程式碼

相關文章