index.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  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 = false, // 请求后错误提示
  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. });
  19. throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
  20. }
  21. token && shoproRequest.setConfig(config => {
  22. config.header.Authorization = token
  23. })
  24. if (toastBefore !== '') {
  25. uni.showLoading({
  26. title: toastBefore,
  27. mask: true
  28. });
  29. }
  30. return config
  31. });
  32. /* 请求之后拦截器 */
  33. shoproRequest.interceptor.response((response) => {
  34. uni.hideLoading();
  35. if (response.code !== 0) {
  36. if (toastAfter) {
  37. uni.showToast({
  38. title: response.msg || '请求出错,稍后重试',
  39. icon: 'none',
  40. duration: 1000,
  41. mask: true
  42. });
  43. }
  44. }
  45. // token过期注销
  46. if (response.code === 161099 || response.code === 160003) {
  47. uni.showToast({
  48. title: '登录已过期或注销',
  49. icon: 'none',
  50. });
  51. throw (`登录已过期或注销,已阻止请求: '${api.url}'`);
  52. }
  53. return response
  54. })
  55. return shoproRequest.request({
  56. url: api.url,
  57. data,
  58. method: api.method
  59. })
  60. }
  61. // 组装接口路径
  62. function getApiPath(url) {
  63. let apiArray = url.split(".");
  64. let api = apiList;
  65. apiArray.forEach(v => {
  66. api = api[v];
  67. });
  68. return api;
  69. }