axios.js 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. console.log(store.getters.type)
  31. if (result === 'confirm') {
  32. const path = '/' + store.getters.type
  33. redirect(path)
  34. }
  35. }
  36. return Promise.reject(res)
  37. })
  38. // 错误拦截
  39. $axios.onError((error) => {
  40. const code = parseInt(error.response && error.response.status)
  41. if (code === 400) {
  42. redirect('/400')
  43. }
  44. })
  45. }