index.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. class Request {
  2. constructor(options = {}) {
  3. // 请求的根路径
  4. this.baseUrl = options.baseUrl || ''
  5. // 请求的 url 地址
  6. this.url = options.url || ''
  7. // 请求方式
  8. this.method = 'GET'
  9. // 请求的参数对象
  10. this.data = null
  11. // header 请求头
  12. this.header = options.header || {}
  13. this.beforeRequest = null
  14. this.afterRequest = null
  15. }
  16. get(url, data = {}) {
  17. this.method = 'GET'
  18. this.url = this.baseUrl + url
  19. this.data = data
  20. return this._()
  21. }
  22. post(url, data = {}) {
  23. this.method = 'POST'
  24. this.url = this.baseUrl + url
  25. this.data = data
  26. return this._()
  27. }
  28. put(url, data = {}) {
  29. this.method = 'PUT'
  30. this.url = this.baseUrl + url
  31. this.data = data
  32. return this._()
  33. }
  34. delete(url, data = {}) {
  35. this.method = 'DELETE'
  36. this.url = this.baseUrl + url
  37. this.data = data
  38. return this._()
  39. }
  40. _() {
  41. // 清空 header 对象
  42. this.header = {}
  43. // 请求之前做一些事
  44. this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
  45. // 发起请求
  46. return new Promise((resolve, reject) => {
  47. let weixin = wx
  48. // 适配 uniapp
  49. if ('undefined' !== typeof uni) {
  50. weixin = uni
  51. }
  52. weixin.request({
  53. url: this.url,
  54. method: this.method,
  55. data: this.data,
  56. header: this.header,
  57. success: (res) => { resolve(res) },
  58. fail: (err) => { reject(err) },
  59. complete: (res) => {
  60. // 请求完成以后做一些事情
  61. this.afterRequest && typeof this.afterRequest === 'function' && this.afterRequest(res)
  62. }
  63. })
  64. })
  65. }
  66. }
  67. export const $http = new Request()