request.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. /**
  2. * Request 0.0.5
  3. * @Class uni-app request网络请求库
  4. * @Author lu-ch
  5. * @Date 2019-06-05
  6. * @Email webwork.s@qq.com
  7. * **/
  8. export default class Request {
  9. config = {
  10. baseUrl: '',
  11. header: {
  12. 'Content-Type': 'application/json;charset=UTF-8'
  13. },
  14. method: 'GET',
  15. dataType: 'json',
  16. responseType: 'text',
  17. success () {
  18. },
  19. fail () {
  20. },
  21. complete () {
  22. }
  23. }
  24. static posUrl (url) { /* 判断url是否为绝对路径 */
  25. return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
  26. }
  27. interceptor = {
  28. request (f) {
  29. if (f) {
  30. Request.requestBeforeFun = f
  31. }
  32. },
  33. response (f) {
  34. if (f) {
  35. Request.requestComFun = f
  36. }
  37. }
  38. }
  39. static requestBeforeFun (config) {
  40. return config
  41. }
  42. static requestComFun (response) {
  43. return response
  44. }
  45. setConfig (f) {
  46. this.config = f(this.config)
  47. }
  48. request (options = {}) {
  49. options.baseUrl = options.baseUrl || this.config.baseUrl
  50. options.dataType = options.dataType || this.config.dataType
  51. options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
  52. options.data = options.data || {}
  53. options.header = options.header || this.config.header
  54. options.method = options.method || this.config.method
  55. return new Promise((resolve, reject) => {
  56. let next = true
  57. let _config = null
  58. options.complete = (response) => {
  59. let statusCode = response.statusCode
  60. response.config = _config
  61. response = Request.requestComFun(response)
  62. if (statusCode === 200) { // 成功
  63. resolve(response)
  64. } else {
  65. reject(response)
  66. }
  67. }
  68. let cancel = (t = 'handle cancel') => {
  69. let err = {
  70. errMsg: t,
  71. config: afC
  72. }
  73. reject(err)
  74. next = false
  75. }
  76. let afC = { ...this.config, ...options }
  77. _config = { ...afC, ...Request.requestBeforeFun(afC, cancel) }
  78. if (!next) return
  79. uni.request(_config)
  80. })
  81. }
  82. get (url, data, options = {}) {
  83. options.url = url
  84. options.data = data
  85. options.method = 'GET'
  86. return this.request(options)
  87. }
  88. post (url, data, options = {}) {
  89. options.url = url
  90. options.data = data
  91. options.method = 'POST'
  92. return this.request(options)
  93. }
  94. }