request.ts 2.5 KB

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