要有遥不可及的梦想,也要有脚踏实地的本事。----------- Grapefruit.Banuit Gang(香柚帮)


经常写小程序的项目,今天讲一下小程序封装接口管理的步骤吧

话不多说,我直接上代码

首先打开util.js文件,随便一个位置

// 封装接口
function fetch(url, data, method) {
  if (method == "GET") {
    var header = { 'Content-Type': 'application/html' }
  } else if (method == "POST") {
    var header = {
      "Content-Type": "application/x-www-form-urlencoded",
    }
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: url,
      data: data,
      method: method,
      header: header,
      success(res) {
        if (res.statusCode == 500) {
          reject(res.errMsg);
          wx.showModal({
            title: '提示',
            content: '网络服务异常,请联系系统管理员!',
            showCancel: false,
          })
          wx.hideLoading();
        } else {
          resolve(res.data);
        }
      },
      fail(e) {
        wx.hideLoading();
        wx.showModal({
          title: '错误信息',
          content: "网络不可用,请检查你的网络设置或者稍后重试。",
          showCancel: false
        });
      }
    })
  })
}
module.exports = {
  fetch: fetch
}

第二步,新建接口管理的js文件,api.js,位置随便放,写入代码

var apiHost = "https://****************/ext/api/"; //线上接口地址
// var apiHost = "http://192.168.1.180:8070/ext/api/"; //本机接口地址
// var apiHost = "https://************/ext/api/"; //测试接口地址

var api = {
  login: apiHost + 'auth2', //登录
  updata_pass: apiHost + 'write/res.users', //修改密码
};
module.exports = api;

最后在页面里面去调接口就行了

formSubmit(e) {
    wx.showLoading({
      title: '登录中...',
    })
    if (e.detail.value.username == "") {
      wx.showToast({
        title: '请输入账号',
        icon: 'none',
        duration: 2000
      })
    } else if (e.detail.value.password == "") {
      wx.showToast({
        title: '请输入密码',
        icon: 'none',
        duration: 2000
      })
    } else {
      var params = {
        login: e.detail.value.username,
        password: e.detail.value.password,
        db: 'test1',
        isaccess: true
      };
      util.fetch(api.login, params, 'GET').then((res) => {
        if (res.code == 'N') {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        } else {
          wx.showToast({
            title: '登录成功',
            icon: 'none',
            duration: 1000
          })
          wx.setStorageSync('session_id', res.return.session_id)
          wx.setStorageSync('uid', res.return.uid)
          wx.setStorageSync('username', res.return.username)
          setTimeout(() => {
            wx.reLaunch({
              url: '/pages/home/index'
            })
          }, 1000)
        }
      })
    }
  },

好了,就这些,有不明白的随时问,希望能有帮助

Logo

欢迎加入 MCP 技术社区!与志同道合者携手前行,一同解锁 MCP 技术的无限可能!

更多推荐