axios.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. console.log(store.getters.routePrefix)
  22. Toast(res.msg || '服务器开小差了')
  23. if (res.msg.indexOf('code been used') > -1) {
  24. try {
  25. redirect(store.getters.routePrefix)
  26. } catch (error) {
  27. console.log(error)
  28. }
  29. }
  30. }
  31. // 登录过期
  32. if (res.code === -99) {
  33. const result = await Dialog.alert({
  34. title: '提示',
  35. message: '登录已过期,请重新登录',
  36. theme: 'round-button',
  37. confirmButtonColor: 'linear-gradient(to left, #404040, #101010)',
  38. })
  39. Vue.prototype.$removeStorage(store.getters.routePrefix, 'userInfo')
  40. store.dispatch('user/logout')
  41. if (result === 'confirm') {
  42. redirect(store.getters.routePrefix)
  43. }
  44. }
  45. return Promise.reject(res)
  46. })
  47. // 错误拦截
  48. $axios.onError((error) => {
  49. const code = parseInt(error.response && error.response.status)
  50. if (code === 400) {
  51. redirect('/400')
  52. }
  53. })
  54. }