axios.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // 引入接口
  2. import initApi from '@/apis/index'
  3. import Vue from 'vue'
  4. import { Dialog, Toast } from 'vant'
  5. export default function (context) {
  6. const { $axios, redirect, store } = context
  7. // 初始化接口及挂载接口
  8. const apiMap = initApi($axios)
  9. Vue.prototype.$http = context.$http = { api: apiMap }
  10. $axios.onRequest((config) => {
  11. $axios.setHeader('X-Token', store.getters.accessToken)
  12. })
  13. // 响应拦截
  14. $axios.onResponse(async (response) => {
  15. const res = response.data
  16. // 请求成功
  17. if (!res.code) return res
  18. // 请求失败
  19. if (res.code === -1) {
  20. Toast(res.msg || 'Error')
  21. }
  22. // 登录过期
  23. if (res.code === -99) {
  24. const result = await Dialog.alert({
  25. title: '提示',
  26. message: '登录已过期,请重新登录',
  27. theme: 'round-button',
  28. confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
  29. })
  30. if (result === 'confirm') {
  31. const path = '/' + store.getters.type
  32. redirect(path)
  33. }
  34. }
  35. return Promise.reject(res)
  36. })
  37. // 错误拦截
  38. $axios.onError((error) => {
  39. const code = parseInt(error.response && error.response.status)
  40. if (code === 400) {
  41. redirect('/400')
  42. }
  43. })
  44. }