request.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. import axios from 'axios'
  2. import store from '@/store'
  3. import Cookies from 'cookies'
  4. import { MessageBox, Message, Loading } from 'element-ui'
  5. import { isAdmin, langFilter } from '@/utils/http.js'
  6. const service = axios.create({
  7. timeout: 5000
  8. })
  9. const lang = localStorage.getItem('lang') || 'cn'
  10. service.interceptors.request.use(
  11. config => {
  12. // if (config.isLoading) {
  13. // startLoading()
  14. // }
  15. if (localStorage.getItem('userToken')) {
  16. config.headers.ApiToken = localStorage.getItem('userToken')
  17. }
  18. return config
  19. },
  20. error => {
  21. return Promise.reject(error)
  22. }
  23. )
  24. service.interceptors.response.use(
  25. response => {
  26. // if (response.config.isLoading) {
  27. // endLoading();
  28. // }
  29. const res = response.data
  30. if (res.code === 0) {
  31. Message({
  32. message: res.msg || 'Error',
  33. type: 'error',
  34. duration: 5 * 1000
  35. })
  36. } else if (res.code === 401) {
  37. localStorage.clear()
  38. Message({
  39. message: 'Login information expired, please log in again',
  40. type: 'error',
  41. duration: 3 * 1000,
  42. onClose: () => {
  43. window.location.href = '/'
  44. }
  45. })
  46. } else if (res.code === 1) {
  47. if (isAdmin()) {
  48. return res
  49. } else {
  50. // 前台响应数据
  51. let { data } = res
  52. res.data = langFilter(data)
  53. return res
  54. }
  55. } else if (res.code === 402) {
  56. Message({
  57. message: 'error',
  58. type: 'error',
  59. duration: 3 * 1000,
  60. })
  61. }
  62. return res
  63. },
  64. error => {
  65. Message({
  66. message: 'error',
  67. type: 'error',
  68. duration: 3 * 1000
  69. })
  70. // endLoading();
  71. return Promise.reject(error)
  72. }
  73. )
  74. let loading
  75. function startLoading() {
  76. loading = Loading.service({
  77. lock: true,
  78. text: '加载中',
  79. background: 'rgba(0, 0, 0, 0.7)'
  80. })
  81. }
  82. function endLoading() {
  83. loading.close()
  84. }
  85. const request = (url, method = 'get', data, isLoading = false) => {
  86. const config = {}
  87. if (data) {
  88. if (method === 'get') {
  89. config.params = data
  90. } else {
  91. config.data = data
  92. }
  93. }
  94. return service({
  95. url,
  96. method,
  97. isLoading,
  98. ...config
  99. })
  100. }
  101. export default request