Home  >  Article  >  WeChat Applet  >  Network-wide introduction to mini program interface request encapsulation examples

Network-wide introduction to mini program interface request encapsulation examples

coldplay.xixi
coldplay.xixiforward
2020-10-14 17:50:572303browse

小program development tutorialToday I will introduce to you the example of mini program interface request encapsulation on the whole network. Come and watch.

Network-wide introduction to mini program interface request encapsulation examples

This article is mainly aimed at some beginners. If there are any shortcomings in the writing, please forgive me!

Create two new js files in the utils folder, one is api.js and the other is requtil.js

api.js

This file is the main api Interface, without further ado, let’s go straight to the code

const request = require('requtil.js')/*Apis 把全部api都存在这里*/const Apis = { 
   /* 用户相关 */
  'login': '/devicecenter/auth/weChtLoin',  'bindUser': '/devicecenter/user/userBindinOpenId',  'genQrCode': '/devicecenter/user/getUserRcode',  
   /* 设备相关 */
  'getDeviceList': '/minipro/group/getDl', // 获取设备列表
  'getDeviceAdd': '/minipro/group/addDl', //  添加设备
  'getDeviceDtl': '/minipro/group/delDl', //  删除设备}/* 定义请求方法 */const user = {  login: function(data) {
    request.get(Apis.login, data)
  },  getSecret: function(data) {
    request.get(Apis.getSecret, data)
  },
}module.exports = {
  ...user
}复制代码

requtil.js

Separately encapsulate WeChat’s wx.request request

const globalsetting = require('globalsetting.js')const baseURL = globalsetting.serverconst util = require('util.js')const ignoreUrls = [  '/auth/weChatLogin',  '/user/userBindingOpenId',  '/user/getSecret',  '/user/getOpenId']var token = ''function post(url, args) {
  args = _prev(url, 'POST', args)
  wx.request(args)
}function get(url, args) {
  args = _prev(url, 'GET', args)
  wx.request(args)
}function put(url, args) {
  args = _prev(url, 'PUT', args)
  wx.request(args)
}function _delete(url, args) {
  args = _prev(url, 'DELETE', args)
  wx.request(args)
}function _prev(url, method, args) {  // console.log('123',args)
  args = args || {}
  args.url = url  if(args.urlparam) 
    args.url += '/' + args.urlparam  var params = parseParams(args)
  params.method = method
  params.success = success(params.success)
  params.fail = fail(params.fail)
  setToken(params)  return params
}// 处理接口是否需要添加header.token方法function setToken(params) {  if (!ignoreUrls.some(url => params.url.match(new RegExp(url)))) {    if (!params.header)
      params.header = { token: getToken() }    else 
      params.header.token = getToken()
  } else {    // console.log('ignore: ', params.url)
  }
}// 处理接口参数方法function parseParams(args) {  var params = Object.assign(args)  if (!(params.url.startsWith('https://') || params.url.startsWith('http://')))
    params.url = baseURL + params.url  if(params.param) {    if (params.url.indexOf('?') > -1 && params.url.indexOf('?') != params.url.length - 1) {
      params.url += '&' 
    } else if(params.url.indexOf('?') == params.url.length -1) {      // 无任何操作
    } else {
      params.url += '?'
    }    var buf = ''
    for(var name in params.param) {      let val = params.param[name];
      buf += name + '=' + encodeURI(typeof val == 'object' ? JSON.stringify(val) : val) + '&'
    }
    params.url += buf
  }  return params
}// 接口返回成功方法function success(callback) {  return function(rs) {    var status = rs.statusCode    if (status == 405) {
      util.errorMsg('请求失败405:\n服务器返回失败')
    } else if(status == 404) {
      util.errorMsg('请求失败404:\n找不到接口')
    }    if(callback) callback(rs.data)
  }
}function fail(callback) {  return function(rs) {    console.log(rs)    if(callback) callback(rs)
  }
}// 获取接口请求回来的tokenfunction _setToken(tk) {
  token = tk
  wx.setStorageSync('token', token)
}复制代码

How to call the page

In the global app.js

import api from './utils/apis.js';
App({    api: api,
})复制代码

index page

Get the api interface through getApp() and customize a function to use it Get the data in the promise method, and then call the getChatRecord method in getDevList to assign the data

const APP = getApp()
getDevList(e){  this.getChatRecord().then(res => {
    wx.hideLoading({      success: (res) => {},
    });    if(res.id == '-1') {
      utils.errorMsg(res.message);
    }else {      console.log(res)
    }
  })
}// 设备列表请求接口getChatRecord (params = {}) {  return new Promise((resolve, reject) => {
    APP.api.getDeviceList({      success: res => {
        resolve(res)
      }
    })
  })
},复制代码

I will make a demo later and put it on github so that you can see it more intuitively

Related free learning recommendations: 小program development tutorial

The above is the detailed content of Network-wide introduction to mini program interface request encapsulation examples. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.im. If there is any infringement, please contact admin@php.cn delete