request.js 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
  1. import Vue from 'vue'
  2. import axios from 'axios'
  3. import {
  4. // baseURL,
  5. contentType,
  6. debounce,
  7. messageName,
  8. requestTimeout,
  9. statusName,
  10. successCode,
  11. /* tokenName, */
  12. } from '@/config'
  13. import store from '@/store'
  14. import qs from 'qs'
  15. import router from '@/router'
  16. import { isArray } from '@/utils/validate'
  17. import { needErrorLog, addErrorLog } from '@/vab/plugins/errorLog'
  18. let loadingInstance
  19. // 操作正常Code数组
  20. const codeVerificationArray = isArray(successCode) ? [...successCode] : [...[successCode]]
  21. const CODE_MESSAGE = {
  22. 0: '未可知错误,可能是因为后端不支持跨域CORS、接口地址不存在等问题引起',
  23. 200: '服务器成功返回请求数据',
  24. 201: '新建或修改数据成功',
  25. 202: '一个请求已经进入后台排队(异步任务)',
  26. 204: '删除数据成功',
  27. 400: '发出信息有误',
  28. 401: '用户没有权限(令牌失效、用户名、密码错误、登录过期)',
  29. 402: '令牌过期',
  30. 403: '用户得到授权,但是访问是被禁止的',
  31. 404: '访问资源不存在',
  32. 406: '请求格式不可得',
  33. 410: '请求资源被永久删除,且不会被看到',
  34. 500: '服务器发生错误',
  35. 502: '网关错误',
  36. 503: '服务不可用,服务器暂时过载或维护',
  37. 504: '网关超时',
  38. }
  39. /**
  40. * axios响应拦截器
  41. * @param data response数据
  42. * @param status HTTP status
  43. * @param statusText HTTP status text
  44. * @returns {Promise<*|*>}
  45. */
  46. const handleData = async ({ data, status = 0, statusText }) => {
  47. if (loadingInstance) loadingInstance.close()
  48. // 若data.code存在,覆盖默认code
  49. let code = data && data[statusName] ? data[statusName] : status
  50. // 若code属于操作正常code,则code修正为200
  51. if (codeVerificationArray.indexOf(code) + 1) code = 200
  52. switch (code) {
  53. case 200:
  54. // 业务层级错误处理,以下是假定restful有一套统一输出格式(指不管成功与否都有相应的数据格式)情况下进行处理
  55. // 例如响应内容:
  56. // 错误内容:{ code: 1, msg: '非法参数' }
  57. // 正确内容:{ code: 200, data: { }, msg: '操作正常' }
  58. // return data
  59. return data
  60. case 401:
  61. store.dispatch('user/resetAll').then(() => router.push({ path: '/login', replace: true }).then(() => {}))
  62. break
  63. case 403:
  64. router.push({ path: '/403' }).then(() => {})
  65. break
  66. }
  67. // 异常处理
  68. // 若data.msg存在,覆盖默认提醒消息
  69. const errMsg = `${
  70. data && data[messageName] ? data[messageName] : CODE_MESSAGE[code] ? CODE_MESSAGE[code] : statusText
  71. }`
  72. Vue.prototype.$baseMessage(errMsg, 'error', 'vab-hey-message-error')
  73. // 是否添加错误日志(与errorHandler钩子触发逻辑一致)
  74. if (needErrorLog()) addErrorLog({ message: errMsg, stack: data, isRequest: true })
  75. return Promise.reject(data)
  76. }
  77. /**
  78. * @description axios初始化
  79. */
  80. const instance = axios.create({
  81. // baseURL,
  82. // eslint-disable-next-line no-undef
  83. baseURL: $GlobalConfig.baseUrl,
  84. timeout: requestTimeout,
  85. headers: {
  86. 'Content-Type': contentType,
  87. },
  88. })
  89. /**
  90. * @description axios请求拦截器
  91. */
  92. instance.interceptors.request.use(
  93. (config) => {
  94. const token = store.getters['user/token']
  95. // 不规范写法 可根据setting.config.js tokenName配置随意自定义headers
  96. // if (token) config.headers[tokenName] = token
  97. // 规范写法 不可随意自定义
  98. if (token) config.headers['Authorization'] = `Bearer ${token}`
  99. if (config.data && config.headers['Content-Type'] === 'application/x-www-form-urlencoded;charset=UTF-8')
  100. config.data = qs.stringify(config.data)
  101. if (debounce.some((item) => config.url.includes(item))) loadingInstance = Vue.prototype.$baseLoading()
  102. return config
  103. },
  104. (error) => {
  105. return Promise.reject(error)
  106. }
  107. )
  108. /**
  109. * @description axios响应拦截器
  110. */
  111. instance.interceptors.response.use(
  112. (response) => handleData(response),
  113. (error) => {
  114. const { response = {} } = error
  115. return handleData(response)
  116. }
  117. )
  118. export default instance