axios封装

import axios from 'axios'
import router from '../router'
import store from '../store'

import { Indicator, Toast } from 'mint-ui'

const isDev = process.env.NODE_ENV === 'development'
const $http = axios.create({
  baseURL: isDev ? 'http://192.168.10.10/' : 'http://103.47.82.43/',
  timeout: 1000 * 10
})

$http.interceptors.request.use(
  config => {
    let token = localStorage.getItem('accessToken') ? localStorage.getItem('accessToken') : store.state.token
    if (token) {
      Object.assign(config.headers, { 'Authorization': token })
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

$http.interceptors.response.use(
  response => {
    if (response.status === 200 && response.data.statu !== 200) {
      errorHandle(response.data.statu, response.data.data)
    }
    return response
  },
  error => {
    const { response } = error
    if (error.toString() === 'Error: timeout of 10000ms exceeded') {
      tip('服务器响应超时')
    }
    if (error.toString() === 'Error: Network Error' && window.navigator.onLine) {
      tip('服务器无响应')
    }
    if (error.toString() === 'Error: Request failed with status code 500') {
      tip('服务器繁忙,请稍后重试!')
    }
    if (response) {
      errorHandle(response.status, response.data.error)
      return Promise.reject(response)
    } else {
      if (!window.navigator.onLine) {
        tip('无网络连接,请稍后重试!')
      }
    }
    return Promise.reject(error)
  }
)

const tip = msg => {
  Indicator.close()
  Toast({
    message: msg,
    forbidClick: true,
    className: 'addClassToast'
  })
}

const toLogin = () => {
  router.replace({
    path: '/login',
    query: {
      redirect: '/login'
    }
  })
}

const errorHandle = (code, other) => {
  switch (code) {
    case 201:
      break
    // 401: 未登录状态
    case 401:
      toLogin()
      break
    // 403: 登录过期
    case 403:
      // tip('登录过期,请重新登录')
      localStorage.removeItem('ylbAppAuthorization')
      store.commit('ylbAppLoginStatus', null)
      setTimeout(() => {
        toLogin()
      }, 500)
      break
    // 404请求不存在
    case 404:
      tip('请求的资源不存在')
      break
    // 503,服务器没启动
    case 503:
      tip('服务器不可用')
      break
    default:
      console.log(code, other)
  }
}

export default $http

你可能感兴趣的:(axios封装)