微信小程序 接口请求统一配置

约定不等于承诺〃 2021-09-18 15:00 759阅读 0赞

1. 文件格式

20190326165738972.png

2. main.js 文件(统一配置接口导出,各个页面按需导入引用)

  1. // 小程序开发api接口统一配置
  2. // 如果你的域名是: https://www.baidu.com/cn 那么这里只要填写 cn
  3. let subDomain = '/cn' // 子域名,没有就等于''
  4. const API_BASE_URL = 'https://www.baidu.com' // 主域名
  5. const request = (url, method, data) => {
  6. let _url = API_BASE_URL + subDomain + url
  7. return new Promise((resolve, reject) => {
  8. wx.request({
  9. url: _url,
  10. method: method,
  11. data: data,
  12. header: {
  13. 'Content-Type': 'application/json'
  14. },
  15. success(request) {
  16. resolve(request.data)
  17. },
  18. fail(error) {
  19. reject(error)
  20. },
  21. complete(aaa) {
  22. // 加载完成
  23. }
  24. })
  25. })
  26. }
  27. /**
  28. * 小程序的promise没有finally方法,自己扩展下
  29. */
  30. Promise.prototype.finally = function (callback) {
  31. var Promise = this.constructor;
  32. return this.then(
  33. function (value) {
  34. Promise.resolve(callback()).then(
  35. function () {
  36. return value;
  37. }
  38. );
  39. },
  40. function (reason) {
  41. Promise.resolve(callback()).then(
  42. function () {
  43. throw reason;
  44. }
  45. );
  46. }
  47. );
  48. }
  49. module.exports = {
  50. request,
  51. // 首页列表接口
  52. getList: data => request('/goods/list','get', data),
  53. // 详情接口
  54. getDetail: (data) => request('/goods/detail','get', data),
  55. }

3. 导入使用

20190326171315575.png

index.js 导入使用

  1. const WXAPI = require('../../wxapi/main')
  2. const app = getApp()
  3. Page({
  4. data: {
  5. list: [],
  6. inputValue:'',
  7. pageNumber: 1,
  8. pageSize: 10,
  9. },
  10. // 加载页面
  11. onLoad: function () {
  12. let that = this;
  13. wx.showLoading({
  14. "mask": true,
  15. "title": "加载中..."
  16. });
  17. WXAPI.getList({ // 接口调用获取列表
  18. keyword: that.data.inputValue,
  19. pageNumber: that.data.pageNumber,
  20. pageSize: that.data.pageSize
  21. }).then(function (res) {
  22. wx.hideLoading()
  23. if (res.code == 200) {
  24. that.setData({
  25. list: res.data.list,
  26. });
  27. }
  28. }).catch(function (e) {
  29. console.log(e)
  30. wx.showToast({
  31. title: e.msg,
  32. icon: 'none'
  33. })
  34. })
  35. },
  36. // 分享
  37. onShareAppMessage: function () {
  38. }
  39. })

发表评论

表情:
评论列表 (有 0 条评论,759人围观)

还没有评论,来说两句吧...

相关阅读