index.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 (toastAfter) {
  36. // console.log(response.msg)
  37. uni.showToast({
  38. title: response.msg || '请求出错,稍后重试',
  39. icon: 'none',
  40. mask: true
  41. });
  42. }
  43. }
  44. if (response.code === 2) {
  45. if (toastAfter) {
  46. // console.log(response.msg)
  47. }
  48. }
  49. // token过期注销
  50. // console.log('sss');
  51. if (response.code === 10401) {
  52. store.dispatch('logout');
  53. // store.dispatch('showAuthModal');
  54. uni.removeStorageSync('token');
  55. store.dispatch('autoLogin');
  56. throw (`登录已过期或注销,已阻止此次API请求: '${api.url}'`);
  57. }
  58. return response
  59. })
  60. return shoproRequest.request({
  61. url: api.url,
  62. data,
  63. method: api.method
  64. })
  65. }
  66. // 组装接口路径
  67. function getApiPath(url) {
  68. let apiArray = url.split(".");
  69. let api = apiList;
  70. apiArray.forEach(v => {
  71. api = api[v];
  72. });
  73. return api;
  74. }