request.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. setTimeout(() => {
  32. wx.reLaunch({
  33. url: '/pages/index/index'
  34. });
  35. }, 1000);
  36. reject(res.data);
  37. } else {
  38. wx.showToast({
  39. title: res.data?.message || '请求错误',
  40. icon: 'none',
  41. duration: 2000
  42. });
  43. reject(res.data);
  44. }
  45. },
  46. fail(err) {
  47. if (loading) wx.hideLoading();
  48. wx.showToast({
  49. title: '网络异常,请重试',
  50. icon: 'none',
  51. duration: 2000
  52. });
  53. reject(err);
  54. }
  55. });
  56. });
  57. }
  58. export default request;