Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to reencapsulate the network request in Mini Program

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces how to re-encapsulate the network request in Mini Program, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article. Now let the editor take you to know about it.

1. Background

Network request operations are inevitably involved in the development of WeChat Mini Programs. The api of the native network request provided by Mini Program is as follows:

Wx.request ({url: 'https://test.com/******', / / is only an example, not the real interface address data: {x:', y:'}, header: {'content-type':' application/json' / / default}, success (res) {console.log (res.data)}})

Where:

Url: the address of the requested background interface

Data: parameters to be carried for the request API

Header: set the header,content-type of the request to application/json by default

Success: for callback after a successful request, res contains the data returned after a successful request.

For more information on the use of wx.request, see the official introduction.

RequestTask | Wechat Open documents

So since the official api is already available, why do you need to repackage it?

2. The reasons for secondary packaging.

First, avoid duplicating code

Avoiding duplicate code is mainly reflected in the following points:

1) when our company calls the backend API, except for the login API, all other API requests need to add token to the request header. If there is no encapsulation, it is troublesome to send token every time the network request is called.

2) when a network request is made, it is often necessary to give a load box to indicate that the user is loading. As shown in the following figure:

At the end of the request, hide the load box:

Second, avoid callback to hell

If there are multiple network requests on a page, and the requests are in a certain order, and the wx.request is an asynchronous operation, 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})}

Does it look like a Russian nesting doll?

In order to avoid this kind of writing, of course, it is encapsulated, and Promise is used in this place.

The introduction of Prolise can be viewed on Liao Xuefeng's official website with a detailed introduction.

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

3. Specific encapsulation implementation

Engineering structure:

Two new files are created under the utils folder.

1) httpUtils.js

The encapsulation of the network request. The specific code is as follows:

Const ui = require ('. / ui') Const BASE_URL = 'https://www.wanandroid.com'/** * Network request request * data to be passed by the obj.data request API * obj.showLoading controls whether loading Loading defaults to false and does not display * obj.contentType defaults to application/json * obj.method request method defaults to GET * interface path of obj.url request * obj.message load data prompt * / function request (obj) {return new Promise (function (resolve) Reject) {if (obj.showLoading) {ui.showLoading (obj.message? Obj.message: 'loading...');} 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, / / add request header header: {'Content-Type': contentType,' token': wx.getStorageSync ('token') / / get saved token} / / successful request success: function (res) {console.log ('=') console.log ('= = API address:'+ obj.url) Console.log ('= = interface parameters:'+ JSON.stringify (data)); console.log ('= = request type:'+ method); console.log ("= = interface status:" + res.statusCode); console.log ("= = interface data:" + JSON.stringify (res.data)) Console.log ('=') if (res.statusCode = = 200) {resolve (res);} else if (res.statusCode = = 401) {/ / authorization expired reject ("login expired"); jumpToLogin () / / Jump to login page} else {/ / request failed reject ("request failed:" + res.statusCode)}} Fail: function (err) {/ / Server connection exception console.log ('=') console.log ('= = interface address:'+ url) console.log ('= = interface parameter:'+ JSON.stringify (data)) console.log ('= = request type:'+ method) console.log (" = = server connection exception ") console.log ('=') reject (" server connection exception ") Please check the network and try again ") }, complete: function () {ui.hideLoading ();}}));} / / Jump to the login page function jumpToLogin () {wx.reLaunch ({url:'/ pages/login/login',})} module.exports = {request,}

There are detailed comments in the code, so I won't explain much here.

2) ui.js

It is mainly a simple encapsulation of wx UI operation. 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) specific call

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

/ / index.jsconst httpUtils = require ('.. /.. / utils/httpUtils') const ui = require ('.. /.. / utils/ui') Page ({data: {str:null,}, onLoad () {}, / / get the interface data getNetInfo () {let obj = {method: "POST", showLoading: true, url: `/ user/register?username=pppooo11&password=pppooo&repassword= ppantio` Message: "registering..."} httpUtils.request (obj) .then (res= > {this.setData ({str:JSON.stringify (res)}) ui.showToast (res.data.errorMsg)}) .catch (err= > {console.log ('ERROR')}) }}) Thank you for reading this article carefully. I hope the article "how to re-encapsulate the Internet request in Mini Program" shared by the editor will be helpful to everyone. At the same time, I also hope that you will support and pay attention to the industry information channel. More related knowledge is waiting for you to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report