request.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. import { getToken, removeToken } from './../utils/auth';
  2. import { extend } from 'umi-request'
  3. import { ElMessage } from 'element-plus'
  4. import cleanDeep from 'clean-deep'
  5. import router from '../router';
  6. import { showLoading, hideLoading } from '../utils/loading'
  7. // import { setLogout } from 'src/actions/users'
  8. // import store from 'src/store'
  9. export interface SearchInitParams {
  10. rows?: string | number;
  11. page?: string | number;
  12. }
  13. export interface InitSearchRespones {
  14. data: {
  15. rows: any[],
  16. [key: string]: any
  17. },
  18. [key: string]: any
  19. }
  20. const request = extend({
  21. requestType: 'form',
  22. timeout: 10000
  23. })
  24. request.interceptors.request.use((url, options: any) => {
  25. let hideLoading = options.hideLoading || false
  26. if(!hideLoading) {
  27. showLoading()
  28. }
  29. const Authorization = getToken()
  30. const tenantId = (localStorage.getItem('tenantId') || '')
  31. const organId = (localStorage.getItem('organId') || '')
  32. const authHeaders: any = {}
  33. if (Authorization && !['/api-auth/usernameLogin', '/api-auth/smsLogin', '/api-auth/code/sendSms'].includes(url)) {
  34. authHeaders.Authorization = Authorization
  35. }
  36. if (tenantId) {
  37. authHeaders.tenantId = tenantId
  38. }
  39. if (organId) {
  40. authHeaders.organId = organId
  41. }
  42. return {
  43. url,
  44. options: {
  45. ...options,
  46. params: cleanDeep(options.params),
  47. headers: {
  48. ...options.headers,
  49. ...authHeaders
  50. }
  51. }
  52. }
  53. })
  54. request.interceptors.response.use(async (res, options) => {
  55. setTimeout(() => {
  56. hideLoading()
  57. }, 200)
  58. console.log(res, options, 'res')
  59. const url = new URL(res.url)
  60. if (res.status > 299 || res.status < 200) {
  61. const msg = '服务器错误,状态码' + res.status
  62. ElMessage.error(msg)
  63. throw new Error(msg)
  64. }
  65. const data = await res.clone().json()
  66. if (data.code !== 200 && data.errCode !== 0) {
  67. const msg = data.msg || '处理失败,请重试'
  68. if(data.code === 401 || data.code === 403) {
  69. ElMessage.error(`登录过期,请重新登录!`)
  70. const url = window.location.href.split('#')[0]
  71. router.push(`/login?redirect=${url}`)
  72. }
  73. if(data.code === 404) {
  74. ElMessage.error(`请求资源不存在!`)
  75. router.push('/404')
  76. }
  77. if (!(data.code === 403 || data.code === 401)) {
  78. ElMessage.error(msg)
  79. }
  80. throw new Error(msg)
  81. }
  82. return res
  83. })
  84. export default request