request.js 2.4 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 modal from 'ant-design-vue/es/modal'
  6. import { VueAxios } from './axios'
  7. // import { ACCESS_TOKEN } from '@/store/mutation-types'
  8. // console.log(process.env.VUE_APP_PRO_NAME)
  9. // 创建 axios 实例
  10. const service = axios.create({
  11. baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  12. timeout: 60000 // 请求超时时间
  13. })
  14. const err = (error) => {
  15. console.log(error.response.data.message, 'error')
  16. if (error.response) {
  17. const status = error.response.status
  18. if ((status == 503 || status == 500) && window.location.pathname != '/user/login') {
  19. notification.destroy()
  20. notification.error({
  21. message: '提示',
  22. description: error.response.data.message
  23. })
  24. }
  25. }
  26. // 超时无法访问服务
  27. if (error.message.indexOf('timeout') >= 0 && window.location.pathname != '/user/login') {
  28. notification.destroy()
  29. notification.error({
  30. message: '提示',
  31. description: '请求超时'
  32. })
  33. }
  34. return Promise.reject(error)
  35. }
  36. // request interceptor
  37. service.interceptors.request.use(config => {
  38. const token = store.getters.token
  39. config.headers['App-Type'] = 1 // 平台类型
  40. if (token) {
  41. config.headers['access-token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  42. }
  43. return config
  44. }, err)
  45. // response interceptor
  46. service.interceptors.response.use((response) => {
  47. console.log(response, 'response.data.status')
  48. const et = sessionStorage.getItem('errorTips')
  49. if (response.data.status == '1001' && !et) {
  50. sessionStorage.setItem('errorTips', 1)
  51. modal.destroyAll()
  52. modal.error({
  53. title: '提示',
  54. content: response.data.message,
  55. onOk () {
  56. sessionStorage.setItem('errorTips', 0)
  57. store.dispatch('Logout').then(() => {
  58. window.location.reload()
  59. })
  60. }
  61. })
  62. }
  63. if ((response.data.status == '401' || response.data.status == '900' || response.data.status == '500') && window.location.pathname != '/user/login') {
  64. notification.destroy()
  65. notification.error({
  66. message: '提示',
  67. description: response.data.message
  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. }