index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. import Request from './request'
  2. import apiList from './apis.js'
  3. import store from '@/common/store/index.js'
  4. const shoproRequest = new Request();
  5. export default function http(
  6. url,
  7. data = {},
  8. toastBefore = '', // 请求前加载提示
  9. toastAfter = true, // 请求后错误提示
  10. ) {
  11. let api = getApiPath(url);
  12. /* 请求之前拦截器 */
  13. shoproRequest.interceptor.request((config, cancel) => {
  14. let token = uni.getStorageSync('token');
  15. if (api.auth && !token) {
  16. store.dispatch('showAuthModal');
  17. uni.hideLoading()
  18. throw (`暂未登录,已阻止此次API请求: '${api.url}'`);
  19. }
  20. token && shoproRequest.setConfig(config => {
  21. config.header.token = token
  22. })
  23. if (toastBefore !== '') {
  24. uni.showLoading({
  25. title: toastBefore,
  26. mask: true
  27. });
  28. }
  29. return config
  30. });
  31. /* 请求之后拦截器 */
  32. shoproRequest.interceptor.response((response) => {
  33. uni.hideLoading();
  34. if (response.code === 1) {
  35. if (response.msg == '用户暂未扫码!') {
  36. return response
  37. }
  38. if (toastAfter) {
  39. // console.log(response.msg)
  40. uni.showToast({
  41. title: response.msg || '请求出错,稍后重试',
  42. icon: 'none',
  43. mask: true
  44. });
  45. }
  46. }
  47. if (response.code === 2) {
  48. if (toastAfter) {
  49. // console.log(response.msg)
  50. }
  51. }
  52. // token过期注销
  53. // console.log('sss');
  54. if (response.code === 10401) {
  55. store.dispatch('logout');
  56. // store.dispatch('showAuthModal');
  57. uni.removeStorageSync('token');
  58. store.dispatch('autoLogin');
  59. throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
  60. }
  61. return response
  62. })
  63. return shoproRequest.request({
  64. url: api.url,
  65. data,
  66. method: api.method
  67. })
  68. }
  69. // 组装接口路径
  70. function getApiPath(url) {
  71. let apiArray = url.split(".");
  72. let api = apiList;
  73. apiArray.forEach(v => {
  74. api = api[v];
  75. });
  76. return api;
  77. }