request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import store from '@/store'
  4. import notification from 'ant-design-vue/es/notification'
  5. import { VueAxios } from './axios'
  6. import { ACCESS_TOKEN } from '@/store/mutation-types'
  7. console.log(process.env.VUE_APP_PRO_NAME)
  8. // 创建 axios 实例
  9. const service = axios.create({
  10. baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  11. timeout: 60000 // 请求超时时间
  12. })
  13. const err = (error) => {
  14. if (error.response) {
  15. const data = error.response.data
  16. if ((error.response.status == 403 || error.response.status == 401) && window.location.pathname != '/user/login') {
  17. notification.destroy()
  18. notification.error({
  19. message: '提示',
  20. description: data.message
  21. })
  22. setTimeout(function () {
  23. store.dispatch('Logout').then(() => {
  24. window.location.reload()
  25. })
  26. }, 2000)
  27. }
  28. }
  29. // 超时无法访问服务
  30. if (error.message.indexOf('timeout') >= 0 && window.location.pathname != '/user/login') {
  31. notification.destroy()
  32. notification.error({
  33. message: '提示',
  34. description: error.message
  35. })
  36. setTimeout(function () {
  37. store.dispatch('Logout').then(() => {
  38. window.location.reload()
  39. })
  40. }, 2000)
  41. }
  42. return Promise.reject(error)
  43. }
  44. // request interceptor
  45. service.interceptors.request.use(config => {
  46. const token = Vue.ls.get(ACCESS_TOKEN)
  47. if (token) {
  48. // config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  49. }
  50. return config
  51. }, err)
  52. // response interceptor
  53. service.interceptors.response.use((response) => {
  54. console.log(response, 'responseresponseresponse')
  55. if (response.data.status == '-1') {
  56. notification.destroy()
  57. notification.error({
  58. message: '提示',
  59. description: response.data.message
  60. })
  61. setTimeout(function () {
  62. store.dispatch('Logout').then(() => {
  63. window.location.reload()
  64. })
  65. }, 2000)
  66. }
  67. if ((response.data.status == '900' || response.data.status == '500') && window.location.pathname != '/user/login') {
  68. notification.destroy()
  69. notification.error({
  70. message: '提示',
  71. description: response.data.message
  72. })
  73. }
  74. return response.data
  75. }, err)
  76. const installer = {
  77. vm: {},
  78. install (Vue) {
  79. Vue.use(VueAxios, service)
  80. }
  81. }
  82. export {
  83. installer as VueAxios,
  84. service as axios
  85. }