How to re-encapsulate network requests in a mini program
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!
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) } })
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' /** * 网络请求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, }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() { }, //获取接口数据 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') }); } })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

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

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

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

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.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function