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

1.  文件格式

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

// 小程序开发api接口统一配置
// 如果你的域名是: https://www.baidu.com/cn 那么这里只要填写 cn
let subDomain = '/cn'  // 子域名,没有就等于''
const API_BASE_URL = 'https://www.baidu.com'  // 主域名


const request = (url, method, data) => {
  let _url = API_BASE_URL + subDomain  + url
  return new Promise((resolve, reject) => {
    wx.request({
      url: _url,
      method: method,
      data: data,
      header: {
        'Content-Type': 'application/json'
      },
      success(request) {
        resolve(request.data)
      },
      fail(error) {
        reject(error)
      },
      complete(aaa) {
        // 加载完成
      }
    })
  })
}

/**
 * 小程序的promise没有finally方法,自己扩展下
 */
Promise.prototype.finally = function (callback) {
  var Promise = this.constructor;
  return this.then(
    function (value) {
      Promise.resolve(callback()).then(
        function () {
          return value;
        }
      );
    },
    function (reason) {
      Promise.resolve(callback()).then(
        function () {
          throw reason;
        }
      );
    }
  );
}

module.exports = {
  request,
  // 首页列表接口
  getList: data => request('/goods/list','get', data),
  // 详情接口
  getDetail: (data) => request('/goods/detail','get', data),

}

3.  导入使用

index.js 导入使用

const WXAPI = require('../../wxapi/main')
const app = getApp()

Page({
  data: {
    list: [],
    inputValue:'',
    pageNumber: 1,
    pageSize: 10,
  },
   // 加载页面
  onLoad: function () { 
   let that = this;
    wx.showLoading({
      "mask": true,
      "title": "加载中..."
    });                  
      WXAPI.getList({  // 接口调用获取列表
      keyword: that.data.inputValue,
      pageNumber: that.data.pageNumber,
      pageSize: that.data.pageSize
    }).then(function (res) {
      wx.hideLoading()
      if (res.code == 200) {
        that.setData({
          list: res.data.list,
        });
      }
    }).catch(function (e) {
      console.log(e)
         wx.showToast({
           title: e.msg,
           icon: 'none'
         })
    }) 
  },
  // 分享
  onShareAppMessage: function () {

  }
})

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

懂懂kkw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值