Small program development - unified request method

Generally, we are used to unifying the methods of the request interface and turning them into public methods.
However, in the applet, it seems to have encountered some problems. The official example is:

this.setData({
    name: 'MINA'
})

This limits the place of the request. It seems that it can only be used in each business page. The parameters of the setData method are not configurable enough.
The following is the solution I got after referring to some materials

util.js

var apiHost = ".....";

//url添加最后的相对路径即可
function getRequest(url, that, targetName) {
  wx.request({
    url: apiHost + url,
    method: 'GET',
    header: {
      'content-type': 'application/json' // 默认值
    },
    success: function (res) {
      var param = {};
      param[targetName] = res.data;
      that.setData(param);
    },
    fail: function (error) {
      console.log(error);
    }
  })
}

function postRequest(url, data, that, targetName ) {
  var token='你的令牌';   //比如存储在Storage中
  wx.request({
        url: apiHost + url,
        data: data,
        method: 'POST',
        header: {
            'content-type': 'application/json', // 默认值
            'Authorization': "Bearer " + token
        },
        success: function (res) {
            var param = {};
            param[targetName] = res.data;
            that.setData(param);
        },
        fail: function (error) {
            console.log(error);
        }
    })
}

module.exports.getRequest = getRequest;
module.exports.postRequest = postRequest;

call api

const util = require('../../utils/util.js')

Page({
  data: {
    logInResult:{},
    sessionKey:"",
  },
  logIn:function(e){
    //登录某系统
    util.postRequest('/Account/LogInForMiniProgram', { "UserName": this.data.userName, "Password": this.data.password }, this, "logInResult");
  },
  wxLogInAndGetSessionKey: function (e) {
    //注意作用域,此处,在wx的方法里面拿到的this不对(http://jsrocks.org/cn/2014/10/arrow-functions-and-their-scope)
    var that = this;
    wx.login({
      success: function (res) {
        console.log(res)
        if (res.code) {
          //调用后端接口获得sessionkey
          util.postRequest('/AccountForMiniProgram/WechatGetSessionKey', { id: res.code }, that, "sessionKey");
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }
    });
  },
  onLoad: function () {
  }
})

sample code

https://github.com/zLulus/NotePractice/tree/dev3/MiniProgramDemo

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324837187&siteId=291194637