request.ts 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import { extend } from 'umi-request'
  2. import cleanDeep from 'clean-deep'
  3. import { browser } from '@/helpers/utils'
  4. import { setLogout, setLoginError } from '@/state'
  5. import { postMessage } from './native-message'
  6. import { ElMessage } from 'element-plus'
  7. export interface SearchInitParams {
  8. rows?: string | number
  9. page?: string | number
  10. }
  11. const request = extend({
  12. // requestType: 'form',
  13. timeout: 20000,
  14. timeoutMessage: '请求超时'
  15. })
  16. // request.use(async (ctx, next) => {
  17. // const { url, options } = ctx.req
  18. // const prefix = options.prefix || '';
  19. // const baseUrl: string = url.replace(prefix, '') || '';
  20. // const linkUrl: string = (ApiRouter as any)[baseUrl];
  21. // if (linkUrl) {
  22. // ctx.req.url = prefix + linkUrl;
  23. // }
  24. // await next();
  25. // })
  26. // 是否是初始化接口
  27. let initRequest = false
  28. request.interceptors.request.use(
  29. (url, options: any) => {
  30. initRequest = options.initRequest || false
  31. const Authorization = sessionStorage.getItem('Authorization') || ''
  32. const authHeaders: any = {}
  33. if (
  34. Authorization &&
  35. ![
  36. '/api-auth/usernameLogin',
  37. '/api-auth/smsLogin',
  38. '/api-auth/code/sendSms'
  39. ].includes(url)
  40. ) {
  41. authHeaders.Authorization = Authorization
  42. }
  43. return {
  44. url,
  45. options: {
  46. ...options,
  47. params: cleanDeep(options.params),
  48. headers: {
  49. ...options.headers,
  50. ...authHeaders
  51. }
  52. }
  53. }
  54. },
  55. { global: false }
  56. )
  57. request.interceptors.response.use(
  58. async res => {
  59. if (res.status > 299 || res.status < 200) {
  60. const msg = '服务器错误,状态码' + res.status
  61. ElMessage.error(msg)
  62. throw new Error(msg)
  63. }
  64. const data = await res.clone().json()
  65. if (data.code !== 200 && data.errCode !== 0) {
  66. let msg = data.msg || data.message || '处理失败,请重试'
  67. if (initRequest) {
  68. if (data.code === 403 || data.code === 401) {
  69. setLogout()
  70. } else {
  71. setLoginError()
  72. }
  73. }
  74. if (!(data.code === 403 || data.code === 401)) {
  75. ElMessage.error(msg)
  76. }
  77. const browserInfo = browser()
  78. if (data.code === 403) {
  79. msg += '403'
  80. if (browserInfo.isApp) {
  81. postMessage({
  82. api: 'login'
  83. })
  84. } else {
  85. setLogout()
  86. }
  87. }
  88. throw new Error(msg)
  89. }
  90. return res
  91. },
  92. { global: false }
  93. )
  94. export default request