request.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. /**
  2. * GET请求封装
  3. */
  4. function get(url, data = {}) {
  5. return request(url, data, 'GET');
  6. }
  7. function put(url, data = {}) {
  8. return request(url, data, 'put');
  9. }
  10. function deletes(url, data = {}) {
  11. return request(url, data, 'delete');
  12. }
  13. /**
  14. * POST请求封装
  15. */
  16. function post(url, data = {}) {
  17. return request(url, data, 'POST');
  18. }
  19. /**
  20. * 微信的request
  21. */
  22. //#ifdef H5
  23. const BASEURL = ''
  24. //#endif
  25. //#ifndef H5
  26. const BASEURL = getApp().globalData.url
  27. //#endif
  28. function request(url, data = {}, method = "GET") {
  29. return new Promise(function(resolve, reject) {
  30. uni.showLoading({
  31. title: "加载中"
  32. });
  33. uni.request({
  34. url: BASEURL + url,
  35. method: method,
  36. data: data,
  37. header: {
  38. 'mini-session': uni.getStorageSync('session') || '',
  39. 'Accept': 'application/json',
  40. 'X-Requested-With': 'XMLHttpRequest',
  41. 'Content-Type': 'application/json'
  42. },
  43. success(res) {
  44. if (res.data) {
  45. if (res.data.error) {
  46. if (res.data.error.code != 404) {
  47. uni.showToast({
  48. title: res.data.error.message,
  49. icon: 'none'
  50. });
  51. }
  52. if (res.data.error.code == 9999) {
  53. uni.clearStorageSync('session');
  54. uni.showToast({
  55. title: '登录失效,请重新登录',
  56. icon: 'none'
  57. });
  58. setTimeout(() => {
  59. uni.reLaunch({
  60. url: '/pages/login/login'
  61. });
  62. }, 1000);
  63. }
  64. reject(res.data.error.message);
  65. } else {
  66. resolve(res.data);
  67. }
  68. } else {
  69. resolve(null);
  70. uni.hideLoading();
  71. }
  72. },
  73. fail(res) {
  74. console.log(res);
  75. uni.showToast({
  76. title: '请求超时,请重试',
  77. icon: 'none'
  78. }); // wx.hideLoading()
  79. }
  80. });
  81. });
  82. }
  83. module.exports = {
  84. get,
  85. post,
  86. put,
  87. deletes,
  88. };