index.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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.statusCode !== 200 || response.data.success === false) {
  41. if (toastAfter) {
  42. if (response.statusCode === 401 || response.statusCode === 502 || response.data.code === 161099) {
  43. uni.showToast({
  44. title: '请重新登录!',
  45. icon: 'none',
  46. duration: 1000,
  47. mask: true
  48. });
  49. uni.redirectTo({
  50. url: '/pages/login/index'
  51. });
  52. } else {
  53. uni.showToast({
  54. title: response.data.message || '请求出错,稍后重试',
  55. icon: 'none',
  56. duration: 1000,
  57. mask: true
  58. });
  59. }
  60. }
  61. }
  62. return response.data
  63. })
  64. return shoproRequest.request({
  65. url: api.url || url,
  66. data,
  67. method: api.method
  68. })
  69. }
  70. // 组装接口路径
  71. function getApiPath(url) {
  72. let api;
  73. let apiArray = url.split(".");
  74. if (apiArray.length == 1) {
  75. api = {
  76. auth: true,
  77. method: "POST",
  78. url: url,
  79. }
  80. } else {
  81. api = apiList;
  82. apiArray.forEach(v => {
  83. api = api[v];
  84. });
  85. }
  86. return api;
  87. }