axios.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. // 引入接口
  2. import initApi from '@/apis/index'
  3. import Vue from 'vue'
  4. import { Dialog, Toast } from 'vant'
  5. // import {} from ''
  6. export default function (context) {
  7. const { $axios, redirect, store } = context
  8. // 初始化接口及挂载接口
  9. const apiMap = initApi($axios)
  10. Vue.prototype.$http = context.$http = { api: apiMap }
  11. // 设置请求头
  12. $axios.onRequest(() => {
  13. $axios.setHeader('X-Token', store.getters.accessToken)
  14. })
  15. // 响应拦截
  16. $axios.onResponse(async (response) => {
  17. const res = response.data
  18. // 请求成功
  19. if (!res.code) return res
  20. // 请求失败
  21. if (res.code === -1) {
  22. console.log(store.getters.routePrefix)
  23. Toast(res.msg || '服务器开小差了')
  24. if (res.msg.indexOf('code been used') > -1) {
  25. try {
  26. redirect(store.getters.routePrefix)
  27. } catch (error) {
  28. console.log(error)
  29. }
  30. }
  31. }
  32. // 登录过期
  33. if (res.code === -99) {
  34. const result = await Dialog.alert({
  35. title: '提示',
  36. message: '登录已过期,请重新登录',
  37. theme: 'round-button',
  38. confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
  39. })
  40. Vue.prototype.$removeStorage(store.getters.routePrefix, 'userInfo')
  41. store.dispatch('user/logout')
  42. if (result === 'confirm') {
  43. redirect(store.getters.routePrefix)
  44. }
  45. }
  46. return Promise.reject(res)
  47. })
  48. // 错误拦截
  49. $axios.onError((error) => {
  50. const code = parseInt(error.response && error.response.status)
  51. if (code === 400) {
  52. redirect('/400')
  53. }
  54. })
  55. }