request.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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.error({
  18. message: '提示',
  19. description: data.message
  20. })
  21. setTimeout(function () {
  22. store.dispatch('Logout').then(() => {
  23. window.location.reload()
  24. })
  25. }, 2000)
  26. }
  27. }
  28. // 超时无法访问服务
  29. if (error.message.indexOf('timeout') >= 0 && window.location.pathname != '/user/login') {
  30. notification.error({
  31. message: '提示',
  32. description: error.message
  33. })
  34. setTimeout(function () {
  35. store.dispatch('Logout').then(() => {
  36. window.location.reload()
  37. })
  38. }, 2000)
  39. }
  40. return Promise.reject(error)
  41. }
  42. // request interceptor
  43. service.interceptors.request.use(config => {
  44. const token = Vue.ls.get(ACCESS_TOKEN)
  45. if (token) {
  46. // config.headers['Access-Token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  47. }
  48. return config
  49. }, err)
  50. // response interceptor
  51. service.interceptors.response.use((response) => {
  52. // console.log(response, 'responseresponseresponse')
  53. if (window.location.pathname != '/user/login') {
  54. if (response.data.status == '900') {
  55. notification.destroy()
  56. notification.error({
  57. message: '提示',
  58. description: response.data.message
  59. })
  60. }
  61. } else {
  62. if (response.data.status == '500') {
  63. notification.destroy()
  64. notification.error({
  65. message: '提示',
  66. description: response.data.message
  67. })
  68. }
  69. }
  70. return response.data
  71. }, err)
  72. const installer = {
  73. vm: {},
  74. install (Vue) {
  75. Vue.use(VueAxios, service)
  76. }
  77. }
  78. export {
  79. installer as VueAxios,
  80. service as axios
  81. }