request.js 1.5 KB

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