request.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import axios from 'axios'
  2. import {
  3. MessageBox,
  4. Message
  5. } from 'element-ui'
  6. import store from '@/store'
  7. import router from '@/router'
  8. import {
  9. getToken,
  10. getShopId,
  11. removeToken
  12. } from '@/utils/auth'
  13. //
  14. const baseURL = process.env.VUE_APP_DOMAIN_PREFIX
  15. // create an axios instance
  16. const service = axios.create({
  17. baseURL,
  18. // withCredentials: true, // send cookies when cross-domain requests
  19. timeout: 150000 // request timeout
  20. })
  21. export const uploadUrl = `${baseURL}/file/upload`
  22. export const WXuploadUrl = `${baseURL}/file/uploadWxMedia` // 直播上传专用
  23. export const QYuploadUrl = `${baseURL}/file/uploadQyMedia` // 微信客服上传专用
  24. // request interceptor
  25. service.interceptors.request.use(
  26. (config) => {
  27. if (store.getters.token) {
  28. config.headers['Authorization-business'] = getToken()
  29. config.headers.shopId = getShopId()
  30. config.headers['Content-Type'] = 'application/json; charset=UTF-8'
  31. // config.headers['type'] = ' business'
  32. }
  33. return config
  34. },
  35. (error) => {
  36. console.log(error)
  37. return Promise.reject(error)
  38. }
  39. )
  40. // response interceptor
  41. service.interceptors.response.use(
  42. (response) => {
  43. const res = response.data
  44. if (response.config.responseType === 'blob') {
  45. return response.data
  46. }
  47. if (res.code !== '') {
  48. Message({
  49. message: res.message || 'Error',
  50. type: 'error',
  51. duration: 5 * 1000
  52. })
  53. // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  54. const tokenerr = [20003, '20003', 20004, '20004', 20005, '20005']
  55. if (tokenerr.includes(res.code)) {
  56. localStorage.clear()
  57. removeToken()
  58. router.push({ path: '/login' })
  59. location.reload()
  60. }
  61. if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  62. MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  63. confirmButtonText: 'Re-Login',
  64. cancelButtonText: 'Cancel',
  65. type: 'warning'
  66. }).then(() => {
  67. store.dispatch('user/resetToken').then(() => {
  68. location.reload()
  69. })
  70. })
  71. }
  72. return Promise.reject(new Error(res.message || 'Error'))
  73. }
  74. return res
  75. },
  76. (error) => {
  77. console.log(error)
  78. Message({
  79. message: '服务器暂无响应,请稍后重试',
  80. type: 'error',
  81. duration: 5 * 1000
  82. })
  83. return Promise.reject(error)
  84. }
  85. )
  86. export default service