request.ts 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. const apiRouter = whiteUrl();
  9. const browserInfo = browser();
  10. const request = extend({
  11. requestType: "form",
  12. timeout: 10000,
  13. });
  14. request.interceptors.request.use(
  15. (url, options) => {
  16. const _prefix = storeData.proxy + storeData.platformApi;
  17. // 只有后台才去设置
  18. if (storeData.platformType === "WEB" && (apiRouter as any)[url]) {
  19. url = (apiRouter as any)[url];
  20. }
  21. const Authorization = getToken();
  22. const authHeaders: any = {};
  23. if (Authorization) {
  24. authHeaders.Authorization = Authorization;
  25. }
  26. return {
  27. url: _prefix + url,
  28. options: {
  29. ...options,
  30. params: cleanDeep(options.params),
  31. data: cleanDeep(options.data),
  32. headers: {
  33. ...options.headers,
  34. ...authHeaders,
  35. },
  36. },
  37. };
  38. },
  39. { global: false }
  40. );
  41. request.interceptors.response.use(
  42. async (res, options) => {
  43. if (res.status > 299 || res.status < 200) {
  44. const msg = res.statusText + ", 状态码" + res.status;
  45. showToast(msg);
  46. }
  47. const data = await res.clone().json();
  48. if (data.code === 5000) {
  49. console.log("🚀 ~ data:", data);
  50. if (browserInfo.isApp) {
  51. postMessage({ api: "login" });
  52. } else {
  53. storeData.status = "error";
  54. showToast(data.message);
  55. window.location.href = `${
  56. /(192|localhost)/.test(location.origin) ? "https://test.lexiaoya.cn" : location.origin
  57. }/classroom`;
  58. throw new Error(data.message);
  59. }
  60. }
  61. if (data.code !== 200 && data.errCode !== 0) {
  62. const msg = data.msg || data.message || "处理失败,请重试";
  63. if (!(data.code === 403 || data.code === 401)) {
  64. // storeData.status = 'error'
  65. // showToast('登录过期');
  66. }
  67. throw new Error(msg);
  68. }
  69. return data;
  70. },
  71. { global: false }
  72. );
  73. export default request;