http.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. import axios from 'axios'
  2. import history from './history'
  3. import { getTokenInfo, removeTokenInfo } from './storage'
  4. import { MessageFu } from './message'
  5. import { domShowFu } from './domShow'
  6. const envFlag = process.env.NODE_ENV === 'development'
  7. const baseUrlTemp = 'https://sit-liushaoqibwg.4dage.com' // 测试环境
  8. // const baseUrlTemp = 'http://192.168.20.61:8072' // 线下环境
  9. const baseFlag = baseUrlTemp.includes('https://')
  10. // 请求基地址
  11. export const baseURL = envFlag ? `${baseUrlTemp}${baseFlag ? '' : '/api/'}` : ''
  12. // 处理 类型“AxiosResponse<any, any>”上不存在属性“code”
  13. declare module 'axios' {
  14. interface AxiosResponse {
  15. code: number
  16. timestamp: string
  17. // 这里追加你的参数
  18. }
  19. }
  20. // 创建 axios 实例
  21. const http = axios.create({
  22. baseURL: `${baseURL}${baseFlag ? '/api/' : ''}`,
  23. timeout: 10000
  24. })
  25. let axajInd = 0
  26. // 请求拦截器
  27. http.interceptors.request.use(
  28. function (config: any) {
  29. // 发请求前打开加载提示
  30. domShowFu('#AsyncSpinLoding', true)
  31. axajInd++
  32. const { token } = getTokenInfo()
  33. if (token) config.headers.token = token
  34. return config
  35. },
  36. function (err) {
  37. return Promise.reject(err)
  38. }
  39. )
  40. let timeId = -1
  41. // 响应拦截器
  42. http.interceptors.response.use(
  43. function (response) {
  44. // 请求回来的关闭加载提示
  45. axajInd--
  46. if (axajInd === 0) {
  47. domShowFu('#AsyncSpinLoding', false)
  48. }
  49. if (response.data.code === 5001 || response.data.code === 5002) {
  50. removeTokenInfo()
  51. history.push('/login')
  52. clearTimeout(timeId)
  53. timeId = window.setTimeout(() => {
  54. MessageFu.warning('登录失效!')
  55. }, 200)
  56. } else if (response.data.code === 0) {
  57. // MessageFu.success(response.data.msg);
  58. } else if (response.data.code !== 3014) MessageFu.warning(response.data.msg)
  59. return response.data
  60. },
  61. async function (err) {
  62. clearTimeout(timeId)
  63. timeId = window.setTimeout(() => {
  64. axajInd = 0
  65. domShowFu('#AsyncSpinLoding', false)
  66. // 如果因为网络原因,response没有,给提示消息
  67. if (!err.response) MessageFu.error('网络繁忙,请稍后重试!')
  68. else {
  69. if (
  70. err.response &&
  71. err.response.data &&
  72. err.response.data.msg &&
  73. err.response.data.msg.length < 30
  74. ) {
  75. MessageFu.error(err.response.data.msg)
  76. // 没有权限
  77. if (err.response.data.code === 5003) {
  78. removeTokenInfo()
  79. history.push('/login')
  80. }
  81. } else MessageFu.error('响应错误,请联系管理员!')
  82. }
  83. }, 100)
  84. return Promise.reject(err)
  85. }
  86. )
  87. // 导出 axios 实例
  88. export default http