request.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { extend } from 'umi-request';
  2. import cleanDeep from 'clean-deep';
  3. import { showLoadingToast, showToast, closeToast } from 'vant';
  4. import { createStorage } from '@/helpers/storage';
  5. import { ACCESS_TOKEN } from '@/store/mutation-types';
  6. const storage = createStorage({ prefixKey: '', storage: sessionStorage });
  7. import { useStudentRegisterStore } from '@/store/modules/student-register-store';
  8. const studentRegisterStore = useStudentRegisterStore();
  9. export interface SearchInitParams {
  10. rows?: string | number;
  11. page?: string | number;
  12. }
  13. const request = extend({
  14. // requestType: 'form',
  15. noAuthorization: false, // 默认添加token,在有的情况下
  16. hideLoading: true, // 默认都不显示加载
  17. timeout: 20000,
  18. timeoutMessage: '请求超时'
  19. });
  20. // 是否是初始化接口
  21. let initRequest = false;
  22. let toast: ReturnType<typeof setTimeout>;
  23. request.interceptors.request.use(
  24. (url, options: any) => {
  25. if (!options.hideLoading) {
  26. clearTimeout(toast);
  27. showLoadingToast({
  28. message: '加载中...',
  29. forbidClick: true,
  30. duration: 0
  31. });
  32. }
  33. initRequest = options.initRequest || false;
  34. const Authorization = storage.get(ACCESS_TOKEN) || '';
  35. const authHeaders: any = {};
  36. if (
  37. Authorization &&
  38. ![
  39. '/edu-app/userlogin',
  40. '/edu-app/smsLogin',
  41. '/edu-app/open/sendSms'
  42. ].includes(url) &&
  43. !options.noAuthorization
  44. ) {
  45. authHeaders.Authorization = Authorization;
  46. }
  47. return {
  48. url,
  49. options: {
  50. ...options,
  51. params: cleanDeep(options.params),
  52. data: cleanDeep(options.data),
  53. headers: {
  54. ...options.headers,
  55. ...authHeaders
  56. }
  57. }
  58. };
  59. },
  60. { global: false }
  61. );
  62. request.interceptors.response.use(
  63. async res => {
  64. toast = setTimeout(() => {
  65. closeToast();
  66. }, 100);
  67. if (res.status > 299 || res.status < 200) {
  68. clearTimeout(toast);
  69. const msg = '服务器错误,状态码' + res.status;
  70. showToast(msg);
  71. throw new Error(msg);
  72. }
  73. const data = await res.clone().json();
  74. // 999 为特殊code码
  75. if (data.code !== 200 && data.errCode !== 0 && data.code !== 999) {
  76. let msg = data.msg || data.message || '处理失败,请重试';
  77. if (!(data.code === 403 || data.code === 5000)) {
  78. clearTimeout(toast);
  79. showToast(msg);
  80. }
  81. if (data.code === 5000 || data.code === 403) {
  82. msg += ' authentication ' + data.code;
  83. studentRegisterStore.studentLoutOut();
  84. }
  85. throw new Error(msg);
  86. }
  87. return res;
  88. },
  89. { global: false }
  90. );
  91. export default request;