index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117
  1. import Request from './request';
  2. import apiList from './api.js'
  3. const shoproRequest = new Request();
  4. export default function http(url,
  5. data = {},
  6. toastBefore = '', // 请求前加载提示
  7. toastAfter = true, // 请求后错误提示
  8. ) {
  9. let api = getApiPath(url);
  10. /* 请求之前拦截器 */
  11. shoproRequest.interceptor.request((config, cancel) => {
  12. let token = uni.getStorageSync('token') || "";
  13. if (api.auth && !token) {
  14. uni.hideLoading();
  15. uni.showLoading({
  16. title: '暂未登录,请先登录',
  17. icon: 'none',
  18. duration: 2000,
  19. });
  20. uni.redirectTo({
  21. url: '/subpkg/pages/login/index',
  22. success: function(res) {}
  23. });
  24. throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
  25. }
  26. token && shoproRequest.setConfig(config => {
  27. config.header.Authorization = token
  28. })
  29. if (toastBefore !== '') {
  30. uni.showLoading({
  31. title: toastBefore,
  32. mask: true
  33. });
  34. }
  35. return config
  36. });
  37. /* 请求之后拦截器 */
  38. shoproRequest.interceptor.response((response) => {
  39. uni.hideLoading();
  40. if (response.code != 0 || response.success === false) {
  41. if (toastAfter) {
  42. uni.showToast({
  43. title: response.message || '请求出错,稍后重试',
  44. icon: 'none',
  45. duration: 2000,
  46. mask: true
  47. });
  48. }
  49. // token过期注销
  50. if (response.code === 161099) {
  51. if (response.message == '当前登录已失效,请重新登录') {
  52. uni.showToast({
  53. title: response.message,
  54. icon: 'none',
  55. duration: 2000
  56. });
  57. uni.removeStorageSync('token');
  58. } else {
  59. uni.showToast({
  60. title: response.message,
  61. icon: 'none',
  62. });
  63. }
  64. throw (`登录已过期或注销,已阻止请求: '${api.url}'`);
  65. }
  66. }
  67. return response
  68. })
  69. let userType = uni.getStorageSync('userType') || "drug";
  70. const userPrefix = {
  71. mcs: "/mcs",
  72. drug: "/drug"
  73. }
  74. return shoproRequest.request({
  75. url: userPrefix[userType] + typeUrl(api),
  76. data,
  77. method: api.method
  78. })
  79. }
  80. function typeUrl(api) {
  81. let tUrl = null;
  82. let userType = uni.getStorageSync('userType') || "drug";
  83. if (api.url) {
  84. tUrl = api.url;
  85. } else {
  86. if (userType === 'mcs') {
  87. tUrl = api.mcsurl;
  88. }
  89. if (userType === 'drug') {
  90. tUrl = api.durgurl;
  91. }
  92. }
  93. return tUrl;
  94. }
  95. // 组装接口路径
  96. function getApiPath(url) {
  97. let api;
  98. let apiArray = url.split(".");
  99. if (apiArray.length == 1) {
  100. api = {
  101. auth: true,
  102. method: "POST",
  103. url: url,
  104. }
  105. } else {
  106. api = apiList;
  107. apiArray.forEach(v => {
  108. api = api[v];
  109. });
  110. }
  111. return api;
  112. }