Table of Contents
1. Background
2. Reasons for secondary encapsulation
##3. Specific encapsulation implementation
Home WeChat Applet Mini Program Development How to re-encapsulate network requests in a mini program

How to re-encapsulate network requests in a mini program

Nov 02, 2021 am 11:16 AM
encapsulation Applets network request

This article will introduce to you the network request encapsulation in the development of WeChat applet, talk about the reasons for secondary encapsulation, and the specific encapsulation implementation. I hope it will be helpful to everyone!

How to re-encapsulate network requests in a mini program

1. Background

When developing WeChat mini programs, network request operations will inevitably be involved. The mini programs provide The API requested by the native network is as follows:

wx.request({
  url: 'https://test.com/******', //仅为示例,并非真实的接口地址
  data: {
    x: '',
    y: ''
  },
  header: {
    'content-type': 'application/json' // 默认值
  },
  success (res) {
    console.log(res.data)
  }
})
Copy after login

Among them:

  • url: is the requested backend interface address;

  • data: Parameters that need to be carried by the request interface;

  • header: Set the request header, content-type defaults to application/json,

  • success: is the callback after the request is successful, res contains the data returned after the request is successful.

For more information on the usage of wx.request, please view the official introduction.

RequestTask | WeChat Open Document

So since the official API has been provided, why does it need to be encapsulated again?

2. Reasons for secondary encapsulation

The first point is to avoid duplicating code

Avoiding duplication of code is mainly reflected in the following points:

1) Our company calls the backend interface. In addition to the login interface, other interface requests need to add tokens to the request header. If there is no encapsulation, Every time you make a network request, you need to pass the token, which is very troublesome.

2) When making network requests, it is often necessary to provide a loading box to prompt the user that it is loading.... As shown in the figure below:

How to re-encapsulate network requests in a mini program

If there is no encapsulation, if you need to pop up the loading box at each network request, you need to write this code repeatedly:

When the request starts, display the loading box.

How to re-encapsulate network requests in a mini program

When the request ends, hide the loading box:

How to re-encapsulate network requests in a mini program

Second point, avoid Callback hell

If a page has multiple network requests, and the requests have a certain order, wx.request is an asynchronous operation, then the most direct result is as follows:

onLoad: function () {
    wx.request({
      url: 'https://test.com/api/test01',
      success:res=>{
        wx.request({
          url: 'https://test.com/api/test02',
          success: res=>{
            wx.request({
              url: 'https://test.com/api/test03',
              success: res=>{
                testDataList: res.content
              }
            })
          }
        })
      }
    })
  },
Copy after login

Doesn’t it look like a Russian matryoshka doll?

In order to avoid this writing method, of course it is encapsulated, and Promise is used here.

For an introduction to Prolise, you can go to Liao Xuefeng’s official website for a detailed introduction.

https://www.liaoxuefeng.com/wiki/1022910821149312/1023024413276544

##3. Specific encapsulation implementation

Project structure :

How to re-encapsulate network requests in a mini program

Two new files were created in the utils folder.

1) httpUtils.js

The encapsulation of network requests, the specific code is as follows:

const ui = require('./ui');
const BASE_URL = 'https://www.wanandroid.com'


/**
 * 网络请求request
 * obj.data 请求接口需要传递的数据
 * obj.showLoading 控制是否显示加载Loading 默认为false不显示
 * obj.contentType 默认为 application/json
 * obj.method 请求的方法  默认为GET
 * obj.url 请求的接口路径 
 * obj.message 加载数据提示语
 */
function request(obj) {
    return new Promise(function(resolve, reject) {
      if(obj.showLoading){
        ui.showLoading(obj.message? obj.message : '加载中...');
      }
      var data = {};
      if(obj.data) {
        data = obj.data;
      }
      var contentType = 'application/json';
      if(obj.contentType){
        contentType = obj.contentType;
      } 
  
      var method = 'GET';
      if(obj.method){
        method = obj.method;
      }
  
      wx.request({
        url: BASE_URL + obj.url,
        data: data,
        method: method,
        //添加请求头
        header: {
          'Content-Type': contentType ,
          'token': wx.getStorageSync('token') //获取保存的token
        },
        //请求成功
        success: function(res) {
          console.log('===============================================================================================')
          console.log('==    接口地址:' + obj.url);
          console.log('==    接口参数:' + JSON.stringify(data));
          console.log('==    请求类型:' + method);
          console.log("==    接口状态:" + res.statusCode);
          console.log("==    接口数据:" + JSON.stringify(res.data));
          console.log('===============================================================================================')
          if (res.statusCode == 200) {
            resolve(res);
          } else if (res.statusCode == 401) {//授权失效
            reject("登录已过期");
            jumpToLogin();//跳转到登录页
          } else {
            //请求失败
            reject("请求失败:" + res.statusCode)
          }
        },
        fail: function(err) {
          //服务器连接异常
          console.log('===============================================================================================')
          console.log('==    接口地址:' + url)
          console.log('==    接口参数:' + JSON.stringify(data))
          console.log('==    请求类型:' + method)
          console.log("==    服务器连接异常")
          console.log('===============================================================================================')
          reject("服务器连接异常,请检查网络再试");
        },
        complete: function() {
          ui.hideLoading();
        }
      })
    });
  }
  

  //跳转到登录页
  function jumpToLogin(){
    wx.reLaunch({
      url: '/pages/login/login',
    })
  }
  
  module.exports = {
    request,
  }
Copy after login

There are details in the code Note, I won’t explain much here.

2) ui.js

is mainly a simple encapsulation of wx UI operations. The code is as follows:

export const showToast = function(content,duration) {
    if(!duration) duration = 2000
    wx.showToast({
        title: content,
        icon: 'none',
        duration: duration,
    })
  }
  
  var isShowLoading = false
  export const showLoading = function(title) {
    if(isShowLoading) return
    wx.showLoading({
        title: title?title:'',
        mask:true,
        success:()=>{
            isShowLoading = true
        }
    })
  }
  
  export const hideLoading = function() {
    if(!isShowLoading) return
    isShowLoading = false
    wx.hideLoading()
  }
Copy after login

3) The specific call

made a network request in index.js. The specific code is as follows:

// index.js
const httpUtils = require('../../utils/httpUtils')
const ui = require('../../utils/ui')

Page({
  data: {
    str:null,
  },

  onLoad() {
  },

  //获取接口数据
  getNetInfo(){
    let obj = {
      method: "POST",
      showLoading: true,
      url:`/user/register?username=pppooo11&password=pppooo&repassword=pppooo`,
      message:"正在注册..."
    }
    httpUtils.request(obj).then(res=>{
      this.setData({
        str:JSON.stringify(res)
      })
      ui.showToast(res.data.errorMsg)
    }).catch(err=>{
      console.log('ERROR')
    });
  }
})
Copy after login
Okay, it ends here. If the above content is helpful to you, don’t forget to give it a like.

The code has been uploaded to github. If you are interested, you can click to download.

https://github.com/YMAndroid/NetWorkDemo

For more programming-related knowledge, please visit:

Introduction to Programming! !

The above is the detailed content of How to re-encapsulate network requests in a mini program. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

Implementing card flipping effects in WeChat mini programs In WeChat mini programs, implementing card flipping effects is a common animation effect that can improve user experience and the attractiveness of interface interactions. The following will introduce in detail how to implement the special effect of card flipping in the WeChat applet and provide relevant code examples. First, you need to define two card elements in the page layout file of the mini program, one for displaying the front content and one for displaying the back content. The specific sample code is as follows: <!--index.wxml-->&l

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

According to news from this site on October 31, on May 27 this year, Ant Group announced the launch of the "Chinese Character Picking Project", and recently ushered in new progress: Alipay launched the "Chinese Character Picking-Uncommon Characters" mini program to collect collections from the society Rare characters supplement the rare character library and provide different input experiences for rare characters to help improve the rare character input method in Alipay. Currently, users can enter the "Uncommon Characters" applet by searching for keywords such as "Chinese character pick-up" and "rare characters". In the mini program, users can submit pictures of rare characters that have not been recognized and entered by the system. After confirmation, Alipay engineers will make additional entries into the font library. This website noticed that users can also experience the latest word-splitting input method in the mini program. This input method is designed for rare words with unclear pronunciation. User dismantling

How uniapp achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

How uniapp can achieve rapid conversion between mini programs and H5 requires specific code examples. In recent years, with the development of the mobile Internet and the popularity of smartphones, mini programs and H5 have become indispensable application forms. As a cross-platform development framework, uniapp can quickly realize the conversion between small programs and H5 based on a set of codes, greatly improving development efficiency. This article will introduce how uniapp can achieve rapid conversion between mini programs and H5, and give specific code examples. 1. Introduction to uniapp unia

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

How to operate mini program registration How to operate mini program registration Sep 13, 2023 pm 04:36 PM

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.

Packaging technology and application in PHP Packaging technology and application in PHP Oct 12, 2023 pm 01:43 PM

Encapsulation technology and application encapsulation in PHP is an important concept in object-oriented programming. It refers to encapsulating data and operations on data together in order to provide a unified access interface to external programs. In PHP, encapsulation can be achieved through access control modifiers and class definitions. This article will introduce encapsulation technology in PHP and its application scenarios, and provide some specific code examples. 1. Encapsulated access control modifiers In PHP, encapsulation is mainly achieved through access control modifiers. PHP provides three access control modifiers,

How to get membership in WeChat mini program How to get membership in WeChat mini program May 07, 2024 am 10:24 AM

1. Open the WeChat mini program and enter the corresponding mini program page. 2. Find the member-related entrance on the mini program page. Usually the member entrance is in the bottom navigation bar or personal center. 3. Click the membership portal to enter the membership application page. 4. On the membership application page, fill in relevant information, such as mobile phone number, name, etc. After completing the information, submit the application. 5. The mini program will review the membership application. After passing the review, the user can become a member of the WeChat mini program. 6. As a member, users will enjoy more membership rights, such as points, coupons, member-exclusive activities, etc.

See all articles