移动储能车V1版本
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

http.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. //utils/http.js
  2. class Request {
  3. constructor(options = {}) {
  4. // 请求的根路径
  5. this.baseUrl = options.baseUrl || 'http://10.168.1.100'
  6. // this.baseUrl = options.baseUrl || 'http://10.168.3.100'
  7. // this.baseUrl =options.baseUrl || 'http://192.168.137.100'
  8. // 请求的 url 地址
  9. this.url = options.url || ''
  10. // 请求方式
  11. this.method = 'GET'
  12. // 请求的参数对象
  13. this.data = null
  14. // header 请求头
  15. this.header = options.header || {}
  16. this.beforeRequest = null
  17. this.afterRequest = null
  18. }
  19. // 添加对header的支持
  20. _mergeHeaders(customHeader = {}) {
  21. return Object.assign({}, this.header, customHeader); // 合并默认header和自定义header
  22. }
  23. get(url, data = {},header = {}) {
  24. // console.log(header);
  25. this.method = 'GET'
  26. this.url = this.baseUrl + url
  27. this.data = data
  28. this.header = this._mergeHeaders(header) // 合并header
  29. return this._()
  30. }
  31. post(url, data = {},header = {}) {
  32. this.method = 'POST'
  33. this.url = this.baseUrl + url
  34. this.data = data
  35. this.header = this._mergeHeaders(header) // 合并header
  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. if(this.baseUrl==''){
  52. this.url ="http://10.168.1.100"+this.url
  53. }
  54. // 清空 header 对象
  55. // this.header = {}
  56. // 请求之前做一些事
  57. this.beforeRequest && typeof this.beforeRequest === 'function' && this.beforeRequest(this)
  58. // 发起请求
  59. return new Promise((resolve, reject) => {
  60. let weixin = wx
  61. // 适配 uniapp
  62. if ('undefined' !== typeof uni) {
  63. weixin = uni
  64. }
  65. weixin.request({
  66. url:this.url,
  67. method: this.method,
  68. data: this.data,
  69. header: this.header,
  70. success: (res) => {
  71. resolve(res)
  72. },
  73. fail: (err) => {
  74. reject(err)
  75. },
  76. complete: (res) => {
  77. // 请求完成以后做一些事情
  78. this.afterRequest && typeof this.afterRequest === 'function' && this.afterRequest(res)
  79. }
  80. })
  81. })
  82. }
  83. }
  84. export const $http = new Request()