vue之axios的高度封装

import axios from 'axios'
import {
  Message,
  MessageBox
} from 'element-ui'
//设置默认头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
// create an axios instance  创建一个axios实例
const service = axios.create({
	baseURL:process.env.BASE_API,// url = base url + request url
    // withCredentials: true,    // send cookies when cross-domain requests   跨域请求时发送cookies
    timeout:50000  // request timeout	请求超时
})
// request interceptor   发送请求拦截器
service.interceptors.request.use(
  config => {
    // do something before request is sent		在发送请求前做的事情

    if (store.getters.token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['X-Token'] = getToken()
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)
// response 响应拦截器
service.interceptors.response.use(
	response =>{
	const res = response.data
	if(response.status ===200 && response.config.responseType === 'blob'){
		return response
	} else if (res.code !==200){
		// 101	登录已失效 102	没有权限 103	账号已被删除或禁用
      if (res.code === 101) {
        if (!showLoginMessageBox) {
          showLoginMessageBox = true
          MessageBox.confirm(
            '你已被登出,请重新登录',
            '确定登出', {
              showCancelButton: false,
              showClose: false,
              confirmButtonText: '重新登录',
              type: 'warning',
              callback: action => {
                showLoginMessageBox = false
                if (action === 'confirm') {
                  removeAuth().then(() => {
                    location.reload() // 为了重新实例化vue-router对象 避免bug
                  }).catch(() => {
                    location.reload()
                  })
                }
              }
            }
          )
        }
      } else if (res.code === 402) {
        if (res.error && Object.prototype.toString.call(res.error) === '[object Array]') {
          res.error = res.error.reduce(function(prev, cur, index, array) {
            return prev + '\r\n' + cur
          })
        }
        Message({
          showClose: true,
          duration: 0,
          customClass: 'el-close-message',
          message: res.error,
          type: 'error'
        })
      } else {
        if (res.error) {
          Message({
            message: res.error,
            type: 'error'
          })
        }
      }
      return Promise.reject(res)
    } else {
      return res
    }
  },
  error => {
    Message({
      message: '网络请求失败,请稍候再试',
      type: 'error'
    })
    return Promise.reject(error)
  }
)

你可能感兴趣的:(vue,element-ui)