request.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if (token) {
  40. config.headers['access-token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  41. }
  42. return config
  43. }, err)
  44. // response interceptor
  45. service.interceptors.response.use((response) => {
  46. // console.log(response, 'response.data.status')
  47. const et = sessionStorage.getItem('errorTips')
  48. if ((response.data.status == '1001' || response.data.status == '1099') && !et) {
  49. sessionStorage.setItem('errorTips', 1)
  50. modal.destroyAll()
  51. modal.error({
  52. title: '提示',
  53. content: response.data.message,
  54. onOk () {
  55. sessionStorage.setItem('errorTips', 0)
  56. store.dispatch('Logout').then(() => {
  57. window.location.reload()
  58. })
  59. }
  60. })
  61. }
  62. if ((response.data.status == '401' || response.data.status == '900' || response.data.status == '500') && window.location.pathname != '/user/login') {
  63. notification.destroy()
  64. notification.error({
  65. message: '提示',
  66. description: response.data.message
  67. })
  68. }
  69. return response.data
  70. }, err)
  71. const installer = {
  72. vm: {},
  73. install (Vue) {
  74. Vue.use(VueAxios, service)
  75. }
  76. }
  77. export {
  78. installer as VueAxios,
  79. service as axios
  80. }