search
HomeWeChat AppletMini Program DevelopmentNetwork-wide introduction to mini program interface request encapsulation examples

小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. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.