https.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { useUserStore } from "@/stores/modules/userStore";
  2. // 开发
  3. export const baseURL = import.meta.env.VITE_APP_BASE_API;
  4. const userStore = useUserStore();
  5. const httpInterceptor = {
  6. invoke(options) {
  7. if (!options.url.startsWith('http')) {
  8. options.url = baseURL + options.url
  9. }
  10. options.timeout = 5 * 60 * 1000;
  11. options.header = {...options.header};
  12. const token = userStore.userInfo?.token;
  13. token && (options.header.Authorization = 'Bearer ' + token);
  14. },
  15. }
  16. uni.addInterceptor('request', httpInterceptor);
  17. export const http = (options) => {
  18. // uni.showLoading({
  19. // title: "加载中...",
  20. // mask: true
  21. // })
  22. return new Promise((resolve, reject) => {
  23. uni.request({
  24. ...options,
  25. customUrl: options.url,
  26. success(result) {
  27. const { data: res } = result;
  28. // uni.hideLoading();
  29. switch(res.code){
  30. case 200:
  31. resolve(res);
  32. break;
  33. case 500:
  34. uni.showToast({ icon: 'none', title: res.msg,duration: 2 * 1000});
  35. reject(res)
  36. break;
  37. case 401:
  38. uni.showToast({ icon: 'none', title: '登录失效, 请重新登录', duration: 2 * 1000, mask: true});
  39. setTimeout(_ => uni.navigateTo({ url: "/pages/login/index" }), 2000);
  40. userStore.clearUserInfo();
  41. reject(res)
  42. break;
  43. default:
  44. uni.showToast({ icon: 'none', title: res.msg || '请求错误', mask: true, duration: 2 * 1000 })
  45. reject(res)
  46. break;
  47. }
  48. },
  49. fail(err) {
  50. // uni.hideLoading();
  51. uni.showToast({
  52. icon: 'none',
  53. title: '网络错误,换个网络试试',
  54. duration: 3 * 1000
  55. })
  56. reject(err)
  57. },
  58. complete() {
  59. },
  60. })
  61. })
  62. }