request.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import axios from 'axios'
  2. import { MessageBox, Message, Loading } from 'element-ui'
  3. import store from '@/store'
  4. import { getToken } from '@/utils/auth'
  5. import Storage from '@/utils/storage'
  6. // import { serverUrl, apiMode } from '@/utils/domain'
  7. // import { serverUrl, apiMode } from '../../public/domain'
  8. import * as Foundation from '@/utils/Foundation'
  9. import md5 from 'js-md5'
  10. import checkToken from '@/utils/checkToken'
  11. import { ERROR_TYPE } from '@/utils/enum/ErrorEnum'
  12. const qs = require('qs')
  13. // create an axios instance
  14. const serverUrl = domain.serverUrl
  15. const apiMode = domain.apiMode
  16. const service = axios.create({
  17. baseURL: serverUrl, // url = base url + request url
  18. // withCredentials: true, // send cookies when cross-domain requests
  19. timeout: 30000, // request timeout
  20. paramsSerializer: params => qs.stringify(params, { arryFormat: 'repeat' })
  21. })
  22. export const mediaRequest = axios.create({
  23. baseURL: domain.mediaUrl,
  24. timeout: 30000,
  25. headers: {
  26. 'Content-Type': 'application/json;charset=UTF-8'
  27. },
  28. paramsSerializer: params => qs.stringify(params, { arryFormat: 'repeat' })
  29. })
  30. // request interceptor
  31. service.interceptors.request.use(
  32. config => {
  33. /** 配置全屏加载 */
  34. if (config.loading) {
  35. const { loading } = config
  36. const is_num = typeof (config.loading) === 'number'
  37. if (is_num) config.loading_num = true
  38. config.loading = Loading.service({
  39. lock: true,
  40. background: `rgba(0, 0, 0, ${is_num ? loading : '0.8'})`,
  41. spinner: 'el-icon-loading'
  42. })
  43. }
  44. // uuid
  45. const uuid = Storage.getItem('calling_uuid')
  46. config.headers['uuid'] = uuid
  47. // 获取访问Token
  48. const accessToken = Storage.getItem('calling_access_token')
  49. if (accessToken) {
  50. if (apiMode === 'prod') {
  51. const uid = Storage.getItem('calling_uuid')
  52. const nonce = Foundation.randomString(6)
  53. const timestamp = parseInt(new Date().getTime() / 1000)
  54. const sign = md5(uid + nonce + timestamp + accessToken)
  55. const _params = { uid, nonce, timestamp, sign }
  56. let params = config.params || {}
  57. params = { ...params, ..._params }
  58. config.params = params
  59. } else {
  60. config.headers['Authorization'] = accessToken
  61. }
  62. }
  63. // do something before request is sent
  64. // config.headers['Content-type'] = 'application/x-www-form-urlencoded;charset=utf-8'
  65. // 如果是put/post请求,用qs.stringify序列化参数
  66. const is_put_post = config.method === 'put' || config.method === 'post' || config.method === 'delete'
  67. // const is_json = config.headers['Content-Type'] === 'application/json'
  68. if (is_put_post && config.headers['Content-Type'] === 'application/json') { // 发送json数据
  69. config.data = JSON.stringify(config.data)
  70. }
  71. if (is_put_post && config.headers['Content-Type'] !== 'application/json') { // 发送表单数据
  72. config.data = qs.stringify(config.data, { arrayFormat: 'repeat' })
  73. }
  74. if (store.getters.token) {
  75. // let each request carry token
  76. // ['X-Token'] is a custom headers key
  77. // please modify it according to the actual situation
  78. config.headers['X-Token'] = getToken()
  79. }
  80. return config
  81. },
  82. error => {
  83. // do something with request error
  84. console.log(error) // for debug
  85. return Promise.reject(error)
  86. }
  87. )
  88. // response interceptor
  89. service.interceptors.response.use(
  90. /**
  91. * If you want to get http information such as headers or status
  92. * Please return response => response
  93. */
  94. /**
  95. * Determine the request status by custom code
  96. * Here is just an example
  97. * You can also judge the status by HTTP Status Code
  98. */
  99. async response => {
  100. await closeLoading(response)
  101. return response.data
  102. // if the custom code is not 20000, it is judged as an error.
  103. // if (res.code !== 20000) {
  104. // Message({
  105. // message: res.message || 'Error',
  106. // type: 'error',
  107. // duration: 5 * 1000
  108. // })
  109. //
  110. // // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
  111. // if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
  112. // // to re-login
  113. // MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
  114. // confirmButtonText: 'Re-Login',
  115. // cancelButtonText: 'Cancel',
  116. // type: 'warning'
  117. // }).then(() => {
  118. // store.dispatch('user/resetToken').then(() => {
  119. // location.reload()
  120. // })
  121. // })
  122. // }
  123. // return Promise.reject(new Error(res.message || 'Error'))
  124. // } else {
  125. // return res
  126. // }
  127. },
  128. async error => {
  129. await closeLoading(error)
  130. const error_response = error.response || {}
  131. const error_data = error_response.data || {}
  132. if (error_response.status === 403) {
  133. if (!Storage.getItem('calling_refresh_token')) return
  134. store.dispatch('user/logout')
  135. window.location.replace(`/login?forward=${location.pathname}`)
  136. return
  137. }
  138. Message({
  139. message: getErrorMgs(error_data.message),
  140. type: 'error',
  141. duration: 5 * 1000
  142. })
  143. return Promise.reject(error_data.message)
  144. }
  145. )
  146. function getErrorMgs(msg) {
  147. if (ERROR_TYPE.getDesc(msg) !== undefined) {
  148. return ERROR_TYPE.getDesc(msg)
  149. } else {
  150. return msg
  151. }
  152. }
  153. /**
  154. * 关闭全局加载
  155. * 延迟200毫秒关闭,以免晃眼睛
  156. * @param target
  157. */
  158. const closeLoading = (target) => {
  159. const { loading, loading_num } = target.config
  160. if (!loading) return true
  161. return new Promise((resolve, reject) => {
  162. setTimeout(() => {
  163. target.config.loading.close()
  164. resolve()
  165. }, loading_num ? 0 : 200)
  166. })
  167. }
  168. export default function request(options) {
  169. // 如果是请求【刷新token、登录、退出】不需要检查token,直接请求。
  170. if (/mgr\/refresh_token|mgr\/login|mgr\/logout|care/.test(options.url.toLocaleLowerCase())) {
  171. return service(options)
  172. }
  173. return new Promise((resolve, reject) => {
  174. checkToken(options).then(() => {
  175. service(options).then(resolve).catch(reject)
  176. })
  177. })
  178. }