request.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. export const BASE_URL = 'https://a.bianyifang.com';
  2. function request({ loading = true, url, method = 'GET', data = {}, header = {} }) {
  3. return new Promise((resolve, reject) => {
  4. if (loading) {
  5. wx.showLoading({
  6. title: '加载中...',
  7. mask: true
  8. });
  9. }
  10. wx.request({
  11. url: BASE_URL + url,
  12. method,
  13. data,
  14. header: {
  15. 'content-type': 'application/json',
  16. 'Authorization': wx.getStorageSync('token') || '',
  17. ...header
  18. },
  19. timeout: 10000,
  20. success(res) {
  21. if (loading) wx.hideLoading();
  22. if (res.statusCode === 200) {
  23. resolve(res.data);
  24. } else if (res.statusCode === 401) {
  25. wx.showToast({
  26. title: '登录已失效,请重新登录',
  27. icon: 'none',
  28. duration: 2000
  29. });
  30. wx.removeStorageSync('token');
  31. wx.removeStorageSync('expires_in');
  32. wx.removeStorageSync('posterCache');
  33. wx.removeStorageSync('userInfo');
  34. wx.removeStorageSync('programConfig');
  35. getApp().globalData.userInfo = null;
  36. getApp().globalData.programConfig = null;
  37. setTimeout(() => {
  38. wx.reLaunch({
  39. url: '/pages/index/index'
  40. });
  41. }, 1000);
  42. reject(res.data);
  43. } else {
  44. wx.showToast({
  45. title: res.data?.message || '请求错误',
  46. icon: 'none',
  47. duration: 2000
  48. });
  49. reject(res.data);
  50. }
  51. },
  52. fail(err) {
  53. if (loading) wx.hideLoading();
  54. wx.showToast({
  55. title: '网络异常,请重试',
  56. icon: 'none',
  57. duration: 2000
  58. });
  59. reject(err);
  60. }
  61. });
  62. });
  63. }
  64. export default request;