request.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. import { extend } from 'umi-request'
  2. import cleanDeep from 'clean-deep'
  3. import { browser, 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. ElMessage.error(msg)
  64. throw new Error(msg)
  65. }
  66. const data = await res.clone().json()
  67. if (data.code !== 200 && data.errCode !== 0) {
  68. const msg = data.msg || data.message || '处理失败,请重试'
  69. if (data.code === 403 || data.code === 401) {
  70. // window.location.href = location.origin
  71. // ElMessage.error(msg)
  72. }
  73. if (!(data.code === 403 || data.code === 401)) {
  74. ElMessage.error(msg)
  75. }
  76. if (data.code === 403) {
  77. removeAuth()
  78. window.location.href = location.origin
  79. ElMessage.error('登录已过期,请重新登录')
  80. }
  81. throw new Error(msg)
  82. }
  83. return res
  84. },
  85. { global: false }
  86. )
  87. export default request