Http.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. class HTTP {
  2. constructor({
  3. baseUrl
  4. }) {
  5. this.baseUrl = baseUrl;
  6. this.hangUp = [];
  7. this.intercept = false;
  8. this.logInAgain = null;
  9. }
  10. request({
  11. url,
  12. data = {},
  13. method = "POST",
  14. header = {
  15. 'content-type': 'application/json'
  16. },
  17. showLoading = ''
  18. }) {
  19. return new Promise((resolve, reject) => {
  20. if (this.intercept && url != '/index/loginbywechat') {
  21. this.hangUp.push({
  22. url,
  23. resolve,
  24. reject,
  25. data,
  26. method,
  27. header,
  28. showLoading
  29. })
  30. } else {
  31. this._request(url, resolve, reject, data, method, header, showLoading);
  32. }
  33. })
  34. }
  35. _request(url, resolve, reject, data, method, header, showLoading) {
  36. if (showLoading) uni.showLoading({
  37. title: showLoading,
  38. mask: true
  39. })
  40. uni.request({
  41. url: this.baseUrl + '/yos/rest' + url,
  42. data: data,
  43. method: method,
  44. header: header,
  45. timeout: 60000,
  46. success: res => {
  47. if (res.data.msg == '登陆状态已过期,请重新登陆!') {
  48. this.intercept = true;
  49. this.hangUp.push({
  50. url,
  51. resolve,
  52. reject,
  53. data,
  54. method,
  55. header,
  56. showLoading
  57. })
  58. if (this.logInAgain == null) this.wechatLogin().then(token => {
  59. Promise.all(this.hangUp.map(v => {
  60. v.data.accesstoken = token;
  61. v.data.date = Date.now()
  62. return this._request(v.url, v.resolve, v.reject, v.data, v.method, v.header, v.showLoading);
  63. })).then(res => {
  64. console.log("重新获取数据")
  65. this.hangUp = []
  66. this.intercept = false;
  67. this.logInAgain = null;
  68. })
  69. })
  70. } else {
  71. resolve(res.data)
  72. }
  73. },
  74. fial: err => reject(err),
  75. complete: (res) => {
  76. if (showLoading) uni.hideLoading()
  77. if (res.errMsg != 'request:ok') uni.showToast({
  78. title: '网络异常,请稍后再试',
  79. icon: "none"
  80. })
  81. }
  82. })
  83. }
  84. }
  85. export {
  86. HTTP
  87. }