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. // 设置请求头
  11. $axios.onRequest(() => {
  12. $axios.setHeader('X-Token', store.getters.accessToken)
  13. })
  14. // 响应拦截
  15. $axios.onResponse(async (response) => {
  16. const res = response.data
  17. // 请求成功
  18. if (!res.code) return res
  19. // 请求失败
  20. if (res.code === -1) {
  21. Toast(res.msg || '服务器开小差了')
  22. }
  23. // 登录过期
  24. if (res.code === -99) {
  25. const result = await Dialog.alert({
  26. title: '提示',
  27. message: '登录已过期,请重新登录',
  28. theme: 'round-button',
  29. confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
  30. })
  31. if (result === 'confirm') {
  32. console.log(store.getters.routePrefix)
  33. redirect(store.getters.routePrefix)
  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. }