


How to re-encapsulate network requests in a mini program
Nov 02, 2021 am 11:16 AMThis 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!
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/******', //僅為示例,并非真實(shí)的接口地址 data: { x: '', y: '' }, header: { 'content-type': 'application/json' // 默認(rèn)值 }, success (res) { console.log(res.data) } })
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.
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:
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.
When the request ends, hide the loading box:
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 } }) } }) } }) },
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 :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' /** * 網(wǎng)絡(luò)請(qǐng)求request * obj.data 請(qǐng)求接口需要傳遞的數(shù)據(jù) * obj.showLoading 控制是否顯示加載Loading 默認(rèn)為false不顯示 * obj.contentType 默認(rèn)為 application/json * obj.method 請(qǐng)求的方法 默認(rèn)為GET * obj.url 請(qǐng)求的接口路徑 * obj.message 加載數(shù)據(jù)提示語 */ 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, //添加請(qǐng)求頭 header: { 'Content-Type': contentType , 'token': wx.getStorageSync('token') //獲取保存的token }, //請(qǐng)求成功 success: function(res) { console.log('===============================================================================================') console.log('== 接口地址:' + obj.url); console.log('== 接口參數(shù):' + JSON.stringify(data)); console.log('== 請(qǐng)求類型:' + method); console.log("== 接口狀態(tài):" + res.statusCode); console.log("== 接口數(shù)據(jù):" + JSON.stringify(res.data)); console.log('===============================================================================================') if (res.statusCode == 200) { resolve(res); } else if (res.statusCode == 401) {//授權(quán)失效 reject("登錄已過期"); jumpToLogin();//跳轉(zhuǎn)到登錄頁(yè) } else { //請(qǐng)求失敗 reject("請(qǐng)求失敗:" + res.statusCode) } }, fail: function(err) { //服務(wù)器連接異常 console.log('===============================================================================================') console.log('== 接口地址:' + url) console.log('== 接口參數(shù):' + JSON.stringify(data)) console.log('== 請(qǐng)求類型:' + method) console.log("== 服務(wù)器連接異常") console.log('===============================================================================================') reject("服務(wù)器連接異常,請(qǐng)檢查網(wǎng)絡(luò)再試"); }, complete: function() { ui.hideLoading(); } }) }); } //跳轉(zhuǎn)到登錄頁(yè) function jumpToLogin(){ wx.reLaunch({ url: '/pages/login/login', }) } module.exports = { request, }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() }
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() { }, //獲取接口數(shù)據(jù) getNetInfo(){ let obj = { method: "POST", showLoading: true, url:`/user/register?username=pppooo11&password=pppooo&repassword=pppooo`, message:"正在注冊(cè)..." } httpUtils.request(obj).then(res=>{ this.setData({ str:JSON.stringify(res) }) ui.showToast(res.data.errorMsg) }).catch(err=>{ console.log('ERROR') }); } })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/NetWorkDemoFor 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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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.

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 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

Geolocation positioning and map display of PHP and mini programs Geolocation positioning and map display have become one of the necessary functions in modern technology. With the popularity of mobile devices, people's demand for positioning and map display is also increasing. During the development process, PHP and applets are two common technology choices. This article will introduce you to the implementation method of geographical location positioning and map display in PHP and mini programs, and attach corresponding code examples. 1. Geolocation in PHP In PHP, we can use third-party geolocation

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

By encapsulating code, C++ functions can improve GUI development efficiency: Code encapsulation: Functions group code into independent units, making the code easier to understand and maintain. Reusability: Functions create common functionality that can be reused across applications, reducing duplication and errors. Concise code: Encapsulated code makes the main logic concise and easy to read and debug.

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.
