request.ts 2.6 KB

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