request.js 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. import {
  2. getToken
  3. } from '@/utils/auth'
  4. import {
  5. getLocale
  6. } from '@/utils/index'
  7. import {
  8. $http
  9. } from '@escook/request-miniprogram'
  10. import store from '@/store'
  11. class Request {
  12. constructor(options = {}) {
  13. // 请求的根路径
  14. this.baseUrl = options.baseUrl || ''
  15. // 请求的 url 地址
  16. this.url = options.url || ''
  17. // 请求方式
  18. this.method = 'GET'
  19. // 请求的参数对象
  20. this.data = null
  21. // header 请求头
  22. this.header = options.header || {}
  23. this.beforeRequest = null
  24. this.afterRequest = null
  25. }
  26. get(url, data = {}) {
  27. this.method = 'GET'
  28. this.url = this.baseUrl + url
  29. this.data = data
  30. return this._()
  31. }
  32. post(url, data = {}) {
  33. this.method = 'POST'
  34. this.url = this.baseUrl + url
  35. this.data = data
  36. return this._()
  37. }
  38. put(url, data = {}) {
  39. this.method = 'PUT'
  40. this.url = this.baseUrl + url
  41. this.data = data
  42. return this._()
  43. }
  44. delete(url, data = {}) {
  45. this.method = 'DELETE'
  46. this.url = this.baseUrl + url
  47. this.data = data
  48. return this._()
  49. }
  50. _() {
  51. // 清空 header 对象
  52. this.header = {}
  53. // 请求之前做一些事
  54. this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
  55. // 发起请求
  56. return new Promise((resolve, reject) => {
  57. let weixin = wx
  58. // 适配 uniapp
  59. if (typeof uni !== 'undefined') {
  60. weixin = uni
  61. }
  62. if (process.env.NODE_ENV !== 'development') {
  63. console.log("请求地址:" + this.url, this.data)
  64. }
  65. weixin.request({
  66. url: this.url,
  67. method: this.method,
  68. data: this.data,
  69. header: this.header,
  70. success: res => {
  71. if (this.afterRequest) {
  72. this.afterRequest(res)
  73. }
  74. },
  75. fail: err => {
  76. reject(err)
  77. },
  78. complete: res => {
  79. resolve(res.data)
  80. },
  81. })
  82. })
  83. }
  84. }
  85. const request = new Request()
  86. /**
  87. * 创建请求
  88. * @param baseURL
  89. */
  90. request.baseUrl = process.env.BASE_API
  91. request.config = {
  92. retry: 3,
  93. retryDelay: 1000,
  94. timeout: 50000,
  95. }
  96. request.beforeRequest = _request => {
  97. _request.header['Language-Set'] = getLocale()
  98. _request.header['X-Requested-With'] = 'XMLHttpRequest'
  99. const apiToken = getToken()
  100. if (apiToken) {
  101. _request.header.token = `${apiToken}`
  102. }
  103. }
  104. request.afterRequest = response => {
  105. if (process.env.NODE_ENV !== 'development') {
  106. console.log("返回数据", response)
  107. }
  108. if (response.header && response.header['authorization']) {
  109. // 刷新token
  110. const token = response.header['authorization'].replace('Bearer ', '')
  111. if (token !== store.getters.token) {
  112. store.commit('SET_TOKEN', token)
  113. }
  114. }
  115. const res = response.data
  116. if (res.code !== 0) {
  117. if (res.code === 401) {
  118. if (res.message === 'Token has expired') {
  119. res.message = '登录超时'
  120. }
  121. store.dispatch('fedLogOut').then(() => {
  122. uni.navigateTo({
  123. url: '/pages/user/login'
  124. })
  125. })
  126. } else {
  127. uni.showModal({
  128. content: res.message || 'Error',
  129. success(r) {
  130. if (r.confirm) {
  131. } else if (r.cancel) {
  132. }
  133. }
  134. })
  135. }
  136. return Promise.reject(new Error(res.message || 'Error'))
  137. } else {
  138. return res
  139. }
  140. }
  141. export default request
  142. /**
  143. * GET请求
  144. * @param {Object} url
  145. * @param {Object} params
  146. */
  147. export const get = (url) => (params) => {
  148. return request.get(url, params)
  149. }
  150. /**
  151. * POST请求
  152. * @param {Object} url
  153. * @param {Object} params
  154. */
  155. export const post = (url) => (params) => {
  156. return request.post(url, params)
  157. }
  158. export const link = (url) => {
  159. return process.env.BASE_API + url
  160. }
  161. export const upload = (url) => (params) => {
  162. return new Promise((resolve, reject) => {
  163. uni.uploadFile({
  164. url: process.env.BASE_API + url,
  165. filePath: params.filePath,
  166. name: params.name || 'file',
  167. header: {
  168. 'X-Requested-With': 'XMLHttpRequest',
  169. 'token': getToken(),
  170. 'Content-Type': 'application/json;charset=UTF-8'
  171. },
  172. success(res) {
  173. if (res.data) {
  174. try {
  175. res.data = JSON.parse(res.data)
  176. resolve(res.data)
  177. return
  178. } catch(e) {}
  179. }
  180. uni.showToast({
  181. icon: 'error',
  182. title: '上传文件失败'
  183. })
  184. },
  185. fail(error) {
  186. uni.showToast({
  187. icon: 'none',
  188. title: error.message
  189. })
  190. reject(error)
  191. }
  192. })
  193. })
  194. }