service2.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. import axios, { AxiosError, AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
  2. import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
  3. import qs from 'qs'
  4. import { getAccessToken, getRefreshToken, getTenantId, removeToken, setToken } from '@/utils/auth'
  5. import errorCode from './errorCode'
  6. import { resetRouter } from '@/router'
  7. import { deleteUserCache } from '@/hooks/web/useCache'
  8. import {langHelper} from '@/utils/langHelper'
  9. import { useLocaleStore } from '@/store/modules/locale'
  10. const config: {
  11. base_url: string
  12. result_code: number | string
  13. default_headers: AxiosHeaders
  14. request_timeout: number
  15. } = {
  16. /**
  17. * api请求基础路径
  18. */
  19. base_url: 'http://192.168.188.190:48080/admin-api',
  20. /**
  21. * 接口成功返回状态码
  22. */
  23. result_code: 200,
  24. /**
  25. * 接口请求超时时间
  26. */
  27. request_timeout: 120000,
  28. /**
  29. * 默认接口请求类型
  30. * 可选值:application/x-www-form-urlencoded multipart/form-data
  31. */
  32. default_headers: 'application/json'
  33. }
  34. // servive
  35. const tenantEnable = import.meta.env.VITE_APP_TENANT_ENABLE
  36. const { result_code, base_url, request_timeout } = config
  37. // const localeStore = useLocaleStore()
  38. // 需要忽略的提示。忽略后,自动 Promise.reject('error')
  39. const ignoreMsgs = [
  40. '无效的刷新令牌', // 刷新令牌被删除时,不用提示
  41. '刷新令牌已过期' // 使用刷新令牌,刷新获取新的访问令牌时,结果因为过期失败,此时需要忽略。否则,会导致继续 401,无法跳转到登出界面
  42. ]
  43. // 是否显示重新登录
  44. export const isRelogin = { show: false }
  45. // Axios 无感知刷新令牌,参考 https://www.dashingdog.cn/article/11 与 https://segmentfault.com/a/1190000020210980 实现
  46. // 请求队列
  47. let requestList: any[] = []
  48. // 是否正在刷新中
  49. let isRefreshToken = false
  50. // 请求白名单,无须token的接口
  51. const whiteList: string[] = ['/login', '/refresh-token']
  52. // 创建axios实例
  53. const service2: AxiosInstance = axios.create({
  54. baseURL: base_url, // api 的 base_url
  55. timeout: request_timeout, // 请求超时时间
  56. withCredentials: false, // 禁用 Cookie 等信息
  57. // 自定义参数序列化函数
  58. paramsSerializer: (params) => {
  59. return qs.stringify(params, { allowDots: true })
  60. }
  61. })
  62. // request拦截器
  63. service2.interceptors.request.use(
  64. (config: InternalAxiosRequestConfig) => {
  65. // 是否需要设置 token
  66. let isToken = (config!.headers || {}).isToken === false
  67. whiteList.some((v) => {
  68. if (config.url && config.url.indexOf(v) > -1) {
  69. return (isToken = false)
  70. }
  71. })
  72. if (getAccessToken() && !isToken) {
  73. config.headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
  74. }
  75. // 设置租户
  76. if (tenantEnable && tenantEnable === 'true') {
  77. const tenantId = getTenantId()
  78. if (tenantId) config.headers['tenant-id'] = tenantId
  79. }
  80. const method = config.method?.toUpperCase()
  81. // 防止 GET 请求缓存
  82. if (method === 'GET') {
  83. config.headers['Cache-Control'] = 'no-cache'
  84. config.headers['Pragma'] = 'no-cache'
  85. }
  86. // 自定义参数序列化函数
  87. else if (method === 'POST') {
  88. const contentType = config.headers['Content-Type'] || config.headers['content-type']
  89. if (contentType === 'application/x-www-form-urlencoded') {
  90. if (config.data && typeof config.data !== 'string') {
  91. config.data = qs.stringify(config.data)
  92. }
  93. }
  94. }
  95. return config
  96. },
  97. (error: AxiosError) => {
  98. // Do something with request error
  99. console.log(error) // for debug
  100. return Promise.reject(error)
  101. }
  102. )
  103. // response 拦截器
  104. service2.interceptors.response.use(
  105. async (response: AxiosResponse<any>) => {
  106. let { data } = response
  107. const config = response.config
  108. if (!data) {
  109. // 返回“[HTTP]请求没有返回值”;
  110. throw new Error()
  111. }
  112. const { t } = useI18n()
  113. // 未设置状态码则默认成功状态
  114. // 二进制数据则直接返回,例如说 Excel 导出
  115. if (
  116. response.request.responseType === 'blob' ||
  117. response.request.responseType === 'arraybuffer'
  118. ) {
  119. // 注意:如果导出的响应为 json,说明可能失败了,不直接返回进行下载
  120. if (response.data.type !== 'application/json') {
  121. return response.data
  122. }
  123. data = await new Response(response.data).json()
  124. }
  125. const code = data.code || result_code
  126. // 获取错误信息
  127. const msg = data.msg || errorCode[code] || errorCode['default']
  128. if (ignoreMsgs.indexOf(msg) !== -1) {
  129. // 如果是忽略的错误码,直接返回 msg 异常
  130. return Promise.reject(msg)
  131. } else if (code === 401) {
  132. // 如果未认证,并且未进行刷新令牌,说明可能是访问令牌过期了
  133. if (!isRefreshToken) {
  134. isRefreshToken = true
  135. // 1. 如果获取不到刷新令牌,则只能执行登出操作
  136. if (!getRefreshToken()) {
  137. return handleAuthorized()
  138. }
  139. // 2. 进行刷新访问令牌
  140. try {
  141. const refreshTokenRes = await refreshToken()
  142. // 2.1 刷新成功,则回放队列的请求 + 当前请求
  143. setToken((await refreshTokenRes).data.data)
  144. config.headers!.Authorization = 'Bearer ' + getAccessToken()
  145. requestList.forEach((cb: any) => {
  146. cb()
  147. })
  148. requestList = []
  149. return service2(config)
  150. } catch (e) {
  151. // 为什么需要 catch 异常呢?刷新失败时,请求因为 Promise.reject 触发异常。
  152. // 2.2 刷新失败,只回放队列的请求
  153. requestList.forEach((cb: any) => {
  154. cb()
  155. })
  156. // 提示是否要登出。即不回放当前请求!不然会形成递归
  157. return handleAuthorized()
  158. } finally {
  159. requestList = []
  160. isRefreshToken = false
  161. }
  162. } else {
  163. // 添加到队列,等待刷新获取到新的令牌
  164. return new Promise((resolve) => {
  165. requestList.push(() => {
  166. config.headers!.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
  167. resolve(service2(config))
  168. })
  169. })
  170. }
  171. } else if (code === 500) {
  172. ElMessage.error(t('sys.api.errMsg500'))
  173. return Promise.reject(new Error(msg))
  174. } else if (code === 901) {
  175. ElMessage.error({
  176. offset: 300,
  177. dangerouslyUseHTMLString: true,
  178. message:
  179. '<div>' +
  180. t('sys.api.errMsg901') +
  181. '</div>' +
  182. '<div> &nbsp; </div>' +
  183. '<div>参考 https://doc.iocoder.cn/ 教程</div>' +
  184. '<div> &nbsp; </div>' +
  185. '<div>5 分钟搭建本地环境</div>'
  186. })
  187. return Promise.reject(new Error(msg))
  188. } else if (code !== 200) {
  189. if (msg === '无效的刷新令牌') {
  190. // hard coding:忽略这个提示,直接登出
  191. console.log(msg)
  192. return handleAuthorized()
  193. } else {
  194. ElNotification.error({ title: msg })
  195. }
  196. return Promise.reject('error')
  197. } else {
  198. // const lang = localeStore.getCurrentLocale.lang
  199. const requestUrl = response.config.url || ''
  200. // 判断是否包含rq/iot路径
  201. if (requestUrl.includes('rq/')||requestUrl.includes('system/dict')||requestUrl.includes('system/auth/get-permission-info')||requestUrl.includes('system/dept/list')
  202. ||requestUrl.includes('system/menu/simple-list')||requestUrl.includes('system/menu/list')||requestUrl.includes('system/dept/simple-list')
  203. ||requestUrl.includes('pms/')||requestUrl.includes('system/user/page')||requestUrl.includes('supplier/base/page')||requestUrl.includes('system/dept/get')
  204. ||requestUrl.includes('system/user/simpleUserList')||requestUrl.includes('system/dept/companyLevelDepts')||requestUrl.includes('system/dept/companyLevelChildrenDepts')
  205. ||requestUrl.includes('system/user/companyDeptsEmployee')||requestUrl.includes('system/dept/specifiedSimpleDepts')) {
  206. const localeStore = useLocaleStore()
  207. const lang = localeStore.getCurrentLocale.lang
  208. if (data&& data.data) {
  209. if (data.data.list) {
  210. if (Array.isArray(data.data.list)) {
  211. const list = langHelper.transformArray(data.data.list, lang)
  212. data.data.list = list;
  213. return data;
  214. }
  215. }else if (data &&Array.isArray(data.data)) {
  216. const list = langHelper.transformArray(data.data, lang)
  217. data.data = list;
  218. return data;
  219. }else if (data && typeof data.data === 'object') {
  220. const object = langHelper.transformObject(data, lang)
  221. data = object
  222. return data
  223. } else {
  224. return data
  225. }
  226. }
  227. }else {
  228. return data
  229. }
  230. // return data
  231. }
  232. },
  233. (error: AxiosError) => {
  234. console.log('err' + error) // for debug
  235. let { message } = error
  236. const { t } = useI18n()
  237. if (message === 'Network Error') {
  238. message = t('sys.api.errorMessage')
  239. } else if (message.includes('timeout')) {
  240. message = t('sys.api.apiTimeoutMessage')
  241. } else if (message.includes('Request failed with status code')) {
  242. message = t('sys.api.apiRequestFailed') + message.substr(message.length - 3)
  243. }
  244. ElMessage.error(message)
  245. return Promise.reject(error)
  246. }
  247. )
  248. const refreshToken = async () => {
  249. axios.defaults.headers.common['tenant-id'] = getTenantId()
  250. return await axios.post(base_url + '/system/auth/refresh-token?refreshToken=' + getRefreshToken())
  251. }
  252. const handleAuthorized = () => {
  253. const { t } = useI18n()
  254. if (!isRelogin.show) {
  255. // 如果已经到登录页面则不进行弹窗提示
  256. if (window.location.href.includes('login')) {
  257. return
  258. }
  259. isRelogin.show = true
  260. ElMessageBox.confirm(t('sys.api.timeoutMessage'), t('common.confirmTitle'), {
  261. showCancelButton: false,
  262. closeOnClickModal: false,
  263. showClose: false,
  264. closeOnPressEscape: false,
  265. confirmButtonText: t('login.relogin'),
  266. type: 'warning'
  267. }).then(() => {
  268. resetRouter() // 重置静态路由表
  269. deleteUserCache() // 删除用户缓存
  270. removeToken()
  271. isRelogin.show = false
  272. // 干掉token后再走一次路由让它过router.beforeEach的校验
  273. window.location.href = window.location.href
  274. })
  275. }
  276. return Promise.reject(t('sys.api.timeoutMessage'))
  277. }
  278. // index.ts
  279. const request = (option: any) => {
  280. const { headersType, headers, ...otherOption } = option
  281. return service2({
  282. ...otherOption,
  283. headers: {
  284. 'Content-Type': headersType || config.default_headers,
  285. ...headers
  286. }
  287. })
  288. }
  289. export default {
  290. get: async <T = any>(option: any) => {
  291. const res = await request({ method: 'GET', ...option })
  292. return res.data as unknown as T
  293. },
  294. post: async <T = any>(option: any) => {
  295. const res = await request({ method: 'POST', ...option })
  296. return res.data as unknown as T
  297. },
  298. postOriginal: async (option: any) => {
  299. const res = await request({ method: 'POST', ...option })
  300. return res
  301. },
  302. delete: async <T = any>(option: any) => {
  303. const res = await request({ method: 'DELETE', ...option })
  304. return res.data as unknown as T
  305. },
  306. put: async <T = any>(option: any) => {
  307. const res = await request({ method: 'PUT', ...option })
  308. return res.data as unknown as T
  309. },
  310. download: async <T = any>(option: any) => {
  311. const res = await request({ method: 'GET', responseType: 'blob', ...option })
  312. return res as unknown as Promise<T>
  313. },
  314. upload: async <T = any>(option: any) => {
  315. option.headersType = 'multipart/form-data'
  316. const res = await request({ method: 'POST', ...option })
  317. return res as unknown as Promise<T>
  318. }
  319. }