Axios类封装

API

import axios from 'axios'
import { getToken, removeToken } from '@/services/auth/utils'
import config from '@/config'
import Vue from 'vue'
import { Message } from 'element-ui'

const showMessage = Symbol('showMessage')
let messageInstance = null
class DonMessage {
  success (options, single = true) {
    this[showMessage]('success', options, single)
  }
  warning (options, single = true) {
    this[showMessage]('warning', options, single)
  }
  info (options, single = true) {
    this[showMessage]('info', options, single)
  }
  error (options, single = true) {
    this[showMessage]('error', options, single)
  }
  [showMessage] (type, options, single) {
    if (messageInstance && single) {
      messageInstance.close() // 先把原来的关闭
    }
    messageInstance = Message[type](options) // 再创建新的消息
  }
}
let message = new DonMessage()

// 创建axios实例
const api = axios.create({
  baseURL: config.API_URL, // 后台 api 的 url
  timeout: 90000, // 请求超时时间
  validateStatus: function (status) {
    return status < 500 // Reject only if the status code is greater than or equal to 500
  }
})

// request拦截器
api.interceptors.request.use(config => {
  config.headers.Authorization = getToken()
  return config
}, error => {
  // Do something with request error
  return Promise.reject(error)
})

// respone拦截器
api.interceptors.response.use(res => {
  if (res.data.status_code === 401) { // TODO
    removeToken()
    message.error(res.data.message || 'token过期,请退出重新登录')
    setTimeout(() => {
      Vue.prototype.hub.$emit('goLogin')
    }, 1000)
    return false
  }
  if (res.data.status_code === 200 && res.data) {
    res.data.ok = true
  }
  return res
}, (error, data) => {
  if (error.request && error.request.readyState === 4 && error.request.status === 0) {
    error.response = {
      status_code: 500,
      message: '请检查网络,稍后重试!'
    }
  } else {
    error.response.status === 500 && (error.response = { message: '服务器开小差,请稍后重试!' })
  }
  console.log('response err:', error)// for debug
  return Promise.reject(error.response)
})

export default api

Base

import api from './api'
import { Message } from 'element-ui'
// service 基础类,只用于继承
class Base {
  /**
   * Get请求
   * @param { String } url
   * @param { Object } params
   * @param { Boolean } mute 是否loading,默认false
   */
  sendGet (url, params, mute = false) {
    return api.get(url, { params }).then(response => {
      if (response.data.status_code !== 200) {
        Message.error(response.data.message || '操作失败')
      }
      return response.data
    }).catch(() => {
      console.log('get error')
    })
  }

  /**
   * Post 请求
   * @param { String } url
   * @param { Object } data
   */
  sendPost (url, data) {
    return api.post(url, data).then(response => {
      return response.data
    }).catch((response) => {
      return response
    })
  }

  /**
   * service 中处理错误信息,一般在 新增,修改,删除等操作中调用
   * @param { res.data } data response 中的data
   * @param { success | error | errorOnly } options 成功或失败的 msg, errorOnly 只提示错误消息
   */
  handleError (data, options = {}) {
    if (data.status_code === 200) {
      if (!options.errorOnly) {
        Message.closeAll()
        Message.success({message: options.success || '操作成功', center: true})
      }
    } else {
      Message.closeAll()
      Message.error(data.message || options.error || '操作失败')
    }
  }

  /**
   * url替换工具方法
   * /test/{name} => /test/savo
   * @param { String } url 传入的 url 地址
   * @param { Object } params 要替换的参数
   */
  parseUrl (url, params) {
    Object.keys(params).forEach(key => {
      var reg = new RegExp('\\{' + key + '\\}')
      url = url.replace(reg, params[key])
    })
    return url
  }
}

export default Base

CRUD

class CRUD extends Base {
  constructor () {
    super()
    this.queryUrl = ''
    this.createUrl = ''
    this.updateUrl = ''
    this.destroyUrl = ''
    this.disabledUrl = ''
  }

  /**
   * 查询方法
   * @param { Object } params get参数
   */
  query (params) {
    return this.sendGet(this.queryUrl, params).then(res => {
      return res
    })
  }

  /**
   * 新增方法
   * @param { Object } params get参数
   */
  create (params) {
    return this.sendPost(this.createUrl, params).then(res => {
      this.handleError(res)
      return res
    })
  }

  /**
   * 修改方法
   * @param { Object } params get参数
   */
  update (params) {
    return this.sendPost(this.updateUrl, params).then(res => {
      this.handleError(res)
      return res
    })
  }

  /**
   * 删除方法
   * @param { Object } params get参数
   */
  destroy (params) {
    return this.sendGet(this.destroyUrl, params).then(res => {
      this.handleError(res)
      return res
    })
  }

  /**
   * 禁用方法
   * @param { Object } params get参数
   */
  disabled (params) {
    return this.sendPost(this.disabledUrl, params).then(res => {
      this.handleError(res)
      return res
    })
  }
}

export default CRUD

使用例子

import CRUD from '../CRUD'

class Contract extends CRUD {
  constructor () {
    super()
    this.topRemindsUrl = 'schools/main_top_remind'
    this.checkContractRoomUrl = '/phoenix/live_room/live_room_contract_check'
  }

  getClassroomStatus (params) {
    return this.sendGet(this.checkContractRoomUrl, params).then(res => {
      return res
    })
  }

  getTopRemindList (params) {
    return this.sendGet(this.topRemindsUrl, params).then(res => {
      return res
    })
  }
}

export default new Contract()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值