request.js 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133
  1. // 封装请求
  2. // 请求域名
  3. const baseUrl = process.env.NODE_ENV === 'development' ? '/Apis' : 'https://biking.okenx.com/'
  4. let LoginFailure = false
  5. // 存储请求信息,当接口正在请求中,不会进行下一次接口请求
  6. const pending = {}
  7. // 处理请求成功
  8. const isHttpSuccess = (stauts) => {
  9. return stauts >= 200 && stauts < 300
  10. }
  11. // 处理请求错误
  12. const errorHandle = (res) => {
  13. // 日志处理 全局错误提示
  14. if (res && res.statusCode !== 200) {
  15. // 浏览器错误
  16. uni.showToast({
  17. title: '系统错误,请联系管理员',
  18. icon: 'none',
  19. duration: 2000
  20. })
  21. } else {
  22. // console.log('errorHandle1', res)
  23. // 服务器错误
  24. uni.showToast({
  25. title: res.data.msg || '系统错误,请联系管理员',
  26. icon: 'none',
  27. duration: 2000
  28. })
  29. }
  30. }
  31. export const request = async (opt = {}) => {
  32. // 考虑与uniapp的接口进行兼容
  33. let headers = {
  34. "Content-Type": "application/x-www-form-urlencoded"
  35. }
  36. const {
  37. data,
  38. success,
  39. fail
  40. } = opt
  41. // pending 中的键名
  42. const key = opt.url + '&' + (opt.method || 'GET')
  43. // 处理请求地址
  44. opt.url = baseUrl + opt.url
  45. // 处理公共参数
  46. opt.data = data
  47. opt.timeout = 5000 // 请求超时时间
  48. opt.header = headers
  49. const result = new Promise((resolve, reject) => {
  50. const handler = uni.request(Object.assign({}, opt, {
  51. success: (res) => {
  52. const data = res.data;
  53. delete pending[key]
  54. if (data.type === 'ok') {
  55. resolve(data.message)
  56. }else if (data.type === '999') {
  57. } else {
  58. uni.showToast({
  59. icon: 'none',
  60. title: data.message || '系统错误'
  61. })
  62. reject(data)
  63. }
  64. },
  65. fail: (e) => {
  66. // console.log('fail = ', e)
  67. reject()
  68. },
  69. complete: () => {
  70. uni.hideLoading()
  71. }
  72. }))
  73. if (pending[key]) {
  74. // 中断请求
  75. pending[key].abort()
  76. }
  77. // setTimeout 让pending[key].abort()执行完成后在存值
  78. setTimeout(() => {
  79. pending[key] = handler
  80. }, 0)
  81. })
  82. return result
  83. }
  84. export const axios = {
  85. get(url, data, options = {}) {
  86. return request({
  87. url,
  88. data,
  89. method: 'GET',
  90. ...options
  91. })
  92. },
  93. post(url, data, options = {}) {
  94. return request({
  95. url,
  96. data,
  97. method: 'POST',
  98. ...options
  99. })
  100. },
  101. getDow(url, data, options = {}) {
  102. // console.log('getDow' , options)
  103. return request({
  104. url,
  105. data,
  106. method: 'GET',
  107. ...options
  108. })
  109. },
  110. }