request.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import { extend } from "umi-request";
  2. import { showToast } from "vant";
  3. import cleanDeep from "clean-deep";
  4. import whiteUrl from "../constant/whiteUrl";
  5. import { storeData } from "../store";
  6. import { browser, getToken } from ".";
  7. import { postMessage } from "./native-message";
  8. import { matchProductApiUrl } from "./index"
  9. import { getQuery } from "/src/utils/queryString";
  10. const apiRouter = whiteUrl();
  11. const browserInfo = browser();
  12. const query = getQuery();
  13. const request = extend({
  14. requestType: "form",
  15. timeout: 10000,
  16. //prefix: 'https://www.baidu.com',
  17. });
  18. // 返回各应用实际的接口api地址
  19. // if (!import.meta.env.DEV) {
  20. // const domainUrl = matchProductApiUrl()
  21. // request.extendOptions({ prefix: domainUrl})
  22. // }
  23. request.interceptors.request.use(
  24. (url, options) => {
  25. // console.log(9999,storeData.proxy,storeData.platformApi,options)
  26. // 内容平台的前缀为cbs-app
  27. const platformApi = options.isContentCenter ? '/cbs-app' : storeData.platformApi
  28. const _prefix = storeData.proxy + platformApi;
  29. /**
  30. * 只有后台才去设置
  31. * 暂时没有用到,先注释掉(2024.1.19)
  32. */
  33. // if (storeData.platformType === "WEB" && (apiRouter as any)[url]) {
  34. // url = (apiRouter as any)[url];
  35. // }
  36. /**
  37. * 区分开发环境和非开发环境
  38. *
  39. */
  40. if (!import.meta.env.DEV) {
  41. const domainUrl = matchProductApiUrl()
  42. url = domainUrl + url
  43. } else {
  44. url = _prefix + url
  45. }
  46. const Authorization = getToken();
  47. const authHeaders: any = {};
  48. // 内容平台的接口不需要传token,需要传签名
  49. if (Authorization && !options.isContentCenter && !options.noToken) {
  50. authHeaders.Authorization = Authorization;
  51. }
  52. return {
  53. url: url,
  54. options: {
  55. ...options,
  56. params: cleanDeep(options.params),
  57. data: cleanDeep(options.data),
  58. headers: {
  59. ...options.headers,
  60. ...authHeaders,
  61. },
  62. },
  63. };
  64. },
  65. { global: false }
  66. );
  67. request.interceptors.response.use(
  68. async (res, options) => {
  69. if (res.status > 299 || res.status < 200) {
  70. const msg = res.statusText + ", 状态码" + res.status;
  71. showToast(msg);
  72. }
  73. const data = await res.clone().json();
  74. if (data.code === 5000) {
  75. return data
  76. }
  77. if (data.code !== 200 && data.errCode !== 0) {
  78. const msg = data.msg || data.message || "处理失败,请重试";
  79. if (!(data.code === 403 || data.code === 401)) {
  80. // storeData.status = 'error'
  81. // showToast('登录过期');
  82. }
  83. throw new Error(msg);
  84. }
  85. return data;
  86. },
  87. { global: false }
  88. );
  89. export default request;