C端小程序
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.

116 line
2.4 KiB

  1. const config = require("../config/config.js");
  2. class HttpBasics {
  3. constructor(address) {
  4. if (address) {
  5. this.address = address;
  6. }
  7. }
  8. /**
  9. * 配置
  10. */
  11. config = config;
  12. /**
  13. * 请求路径前缀
  14. */
  15. address = config.url;
  16. /**
  17. * 请求头
  18. */
  19. headers = {
  20. "Content-Type": "application/json;charset=UTF-8",
  21. token: ""
  22. };
  23. /**
  24. * 设置token
  25. * @param {*} token
  26. */
  27. setToken(token) {
  28. this.headers.token = token;
  29. }
  30. /**
  31. * 获取数据
  32. * @param {url,data,headers} param0
  33. */
  34. get({ url, data, headers }) {
  35. headers = { ...this.headers, ...headers };
  36. url = `${this.address}${url}`;
  37. // wx.showLoading({
  38. // title: 'loading...',
  39. // })
  40. return new Promise((resolve, reject) => {
  41. wx.request({
  42. url: url,
  43. header: headers,
  44. data: data,
  45. method: "Get",
  46. success: res => {
  47. // wx.hideLoading();
  48. this.responseMap(res, resolve, reject);
  49. },
  50. fail: err => {
  51. // wx.hideLoading();
  52. reject(err);
  53. }
  54. });
  55. });
  56. }
  57. /**
  58. * 提交数据
  59. * @param {url,data,headers} param0
  60. */
  61. post({ url, data, headers }) {
  62. headers = { ...this.headers, ...headers };
  63. url = `${this.address}${url}`;
  64. // wx.showLoading({
  65. // title: 'loading...',
  66. // })
  67. return new Promise((resolve, reject) => {
  68. wx.request({
  69. url: url,
  70. header: headers,
  71. data: data,
  72. method: "POST",
  73. success: res => {
  74. wx.hideLoading();
  75. this.responseMap(res, resolve, reject);
  76. },
  77. fail: err => {
  78. // wx.hideLoading();
  79. reject(err);
  80. },
  81. complete: res => {}
  82. });
  83. });
  84. }
  85. /**
  86. * 过滤 请求信息
  87. * @param {*} res
  88. * @param {*} resolve
  89. * @param {*} reject
  90. */
  91. responseMap = (res, resolve, reject) => {
  92. console.log(res);
  93. // 网络状态码200
  94. if (res.statusCode == 200) {
  95. // 服务器code 200 成功
  96. if (res.data.code == 200) {
  97. resolve(res.data);
  98. } else {
  99. // wx.hideLoading();
  100. // wx.showToast({
  101. // title: res.data.message,
  102. // image:'./../../assets/img/fail.png'
  103. // });
  104. reject(res.data);
  105. }
  106. }
  107. else {
  108. console.log("请求出错:", res);
  109. reject(res.data);
  110. }
  111. };
  112. /** 日志 */
  113. log(url, body, headers) {}
  114. }
  115. module.exports = new HttpBasics();