index.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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.showToast({
  16. title: '暂未登录,请先登录',
  17. icon: 'none',
  18. duration: 2000,
  19. });
  20. uni.navigateTo({
  21. url: '/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: 1000,
  46. mask: true
  47. });
  48. }
  49. // token过期注销
  50. if (response.code === 161099) {
  51. if (response.message == '当前登录已失效,请重新登录') {
  52. uni.navigateTo({
  53. url: '/pages/login/index',
  54. success: function(res) {}
  55. });
  56. uni.removeStorageSync('token');
  57. } else {
  58. uni.showToast({
  59. title: response.message,
  60. icon: 'none',
  61. });
  62. }
  63. throw (`登录已过期或注销,已阻止请求: '${api.url}'`);
  64. }
  65. }
  66. return response
  67. })
  68. return shoproRequest.request({
  69. url: api.url || url,
  70. data,
  71. method: api.method
  72. })
  73. }
  74. // 组装接口路径
  75. function getApiPath(url) {
  76. let api;
  77. let apiArray = url.split(".");
  78. if (apiArray.length == 1) {
  79. api = {
  80. auth: true,
  81. method: "POST",
  82. url: url,
  83. }
  84. } else {
  85. api = apiList;
  86. apiArray.forEach(v => {
  87. api = api[v];
  88. });
  89. }
  90. return api;
  91. }