http.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. import { noEmpty } from '@utils'
  2. const Http = (options = { data: {} }) => {
  3. return new Promise((resolve, reject) => {
  4. if (options.loadingStr === 'loading') {
  5. uni.showLoading({
  6. mask: true,
  7. title: '加载中..'
  8. })
  9. }
  10. let token = uni.getStorageSync('MD_token') || ''
  11. let header = {
  12. 'Content-Type': 'application/json',
  13. 'token': token,
  14. // 'Content-Type': 'application/x-www-form-urlencoded'
  15. }
  16. let params = {...options.data}
  17. if (uni.getStorageSync('APP_token')) params.token = uni.getStorageSync('APP_token')
  18. for (let key in options.data) {
  19. if (options.data[key] === undefined || options.data[key] === 'undefined') {
  20. params[key] = ''
  21. }
  22. }
  23. let url = uni.baseUrl + options.url
  24. // let url = options.url
  25. if (options.queryData) {
  26. let qStr = ''
  27. for(let k in options.queryData) {
  28. qStr += `${k}=${options.queryData[k]}&`
  29. }
  30. qStr = qStr.substr(0, qStr.length - 1)
  31. url += `?${qStr}`
  32. }
  33. uni.request({
  34. url,
  35. data: {
  36. ...params
  37. },
  38. header,
  39. method: options.method || 'POST',
  40. complete: res => {
  41. if (options.loadingStr === 'loading') {
  42. uni.hideLoading()
  43. }
  44. },
  45. success: res => {
  46. const { data: cData } = res
  47. const code = cData.errno
  48. switch (code) {
  49. case 0:
  50. return resolve(noEmpty(cData.data) ? cData.data : cData)
  51. break
  52. case 401:
  53. case 404:
  54. case 405:
  55. uni.removeStorageSync('MD_userInfo')
  56. uni.removeStorageSync('MD_token')
  57. // 差一个补是否绑定微信
  58. if (uni.getStorageSync('APP_token')) {
  59. uni.login({
  60. success: function (res) {
  61. if (res.code) {
  62. uni.api.base.apiwxautologin({code: res.code}).then(cData => {
  63. if (cData.token === 'error') {
  64. uni.removeStorageSync('APP_token')
  65. } else {
  66. uni.setStorageSync('APP_userInfo', cData)
  67. uni.setStorageSync('APP_token', cData.token)
  68. }
  69. })
  70. }
  71. }
  72. })
  73. } else {
  74. uni.showToast({
  75. title: `请先登录~`,
  76. icon: 'none',
  77. })
  78. }
  79. uni.navigateTo({
  80. url: '/pages/user/login/login'
  81. })
  82. break
  83. default:
  84. uni.showModal({
  85. title: '提示',
  86. content: `${cData.errmsg}(${code})`,
  87. })
  88. return reject(cData)
  89. }
  90. // resolve()
  91. },
  92. fail: err => {
  93. console.log(err)
  94. reject(err)
  95. }
  96. })
  97. })
  98. }
  99. // export default Http
  100. function request (url, data, loadingStr, queryData) {
  101. return Http({
  102. url,
  103. data,
  104. loadingStr,
  105. queryData,
  106. })
  107. }
  108. export {
  109. request,
  110. }