Whole network applet interface request encapsulation example code

  • 2021-09-16 06:02:29
  • OfStack

Preface

This article is mainly aimed at some beginners, and there are some bad places to write. Please understand a lot!

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

api.js

This file mainly api interface, nonsense not to say directly on the code


const request = require('requtil.js')
/*Apis  Put all of it api They all exist here */
const Apis = { 
 /*  User-related  */
 'login': '/devicecenter/auth/weChtLoin',
 'bindUser': '/devicecenter/user/userBindinOpenId',
 'genQrCode': '/devicecenter/user/getUserRcode',
 
 /*  Equipment correlation  */
 'getDeviceList': '/minipro/group/getDl', //  Get a list of devices 
 'getDeviceAdd': '/minipro/group/addDl', //  Add a device 
 'getDeviceDtl': '/minipro/group/delDl', //  Delete a device 
}
/*  Define the request method  */
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 the wx. request request of WeChat


const globalsetting = require('globalsetting.js')
const baseURL = globalsetting.server
const 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
}
//  Does the processing interface need to be added header.token Method 
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)
 }
}
//  Method for processing interface parameters 
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) {
  //  Nothing to do 
 } 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
}
//  Interface returns the success method 
function success(callback) {
 return function(rs) {
 var status = rs.statusCode
 if (status == 405) {
  util.errorMsg(' Request failed 405 : \n Server returns failure ')
 } else if(status == 404) {
  util.errorMsg(' Request failed 404 : \n Interface not found ')
 }
 if(callback) callback(rs.data)
 }
}

function fail(callback) {
 return function(rs) {
 console.log(rs)
 if(callback) callback(rs)
 }
}
//  Object returned by the interface request token
function _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

Obtain api interface through getApp (), use promise method to obtain data in a custom function, and then call getChatRecord method in getDevList to assign 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)
 }
 })
}
//  Device list request interface 
getChatRecord (params = {}) {
 return new Promise((resolve, reject) => {
 APP.api.getDeviceList({
  success: res => {
  resolve(res)
  }
 })
 })
},

Later, I will make an demo and put it on top of github, so that you look more intuitive. 1

Summarize


Related articles: