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 encapsulate the Network request in WeChat Mini Programs

2025-02-27 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article introduces the relevant knowledge of "how to encapsulate the network request in WeChat Mini Programs". In the operation of the actual case, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Detailed explanation of WeChat Mini Programs's Network request simple Encapsulation example

Realizing the network request in WeChat Mini Programs feels much simpler than the Android. We only need to use the API provided by it to solve the network request problem.

Normal HTTPS request (wx.request)

Upload files (wx.uploadFile)

Download file (wx.downloadFile)

WebSocket Communications (wx.connectSocket)

For data security, WeChat Mini Programs network request only supports https, of course, the meaning of each parameter is not detailed, if you are not familiar with it, you can read the official document network request api, when we use request, the content-typ of header defaults to application/json, indicating in the document that the value of method must be uppercase, but after testing, the request can also be successful in lowercase. The default timeout for request is 60s. If we want to customize the timeout, we can add the following code snippet to app.json to set the request,socket and the timeout for uploading and downloading files, respectively.

"networkTimeout": {"request": 5000, "connectSocket": 5000, "uploadFile": 5000, "downloadFile": 5000}

After setting the timeout, we begin to encapsulate network requests. Usually, the network requests we come into contact with are generally divided into two categories, one is running in the background, there is no prompt to load the dialog box, and the other is a hint. If the prompt is loading data, then we will use this as a clue to encapsulate. First create a network network request utility class, and then

/ / url: network request of progress bar / / url: url// params of network request: request parameters / / message: prompt message of progress bar / / success: successful callback function / / fail: failed callback function requestLoading (url, params, message, success, fail) {console.log (params) wx.showLoading ({title: message,}) wx.request ({url: url, data: params Header: {'content-type':' application/x-www-form-urlencoded'}, method: 'post', success: function (res) {/ / console.log (res.data) wx.hideLoading () if (res.statusCode = = 200) {success (res.data)} else {fail ()}}, fail: function (res) {wx.hideLoading () fail ()} Complete: function (res) {},})}

The above function is easy to understand, and the meaning of the parameters has been explained in the code. Before the network request starts, the Loading dialog box is displayed to remind the user that the current network is requesting data. When the network request succeeds or fails, call wx.hideLoading () to cancel the display of the prompt box. Wx.showNavigationBarLoading () is also provided in api to display the navigation bar loading animation of the current page, so if we want to show this animation, we can call wx.showNavigationBarLoading () at the beginning of the requestLoading execution, and then call wx.hideNavigationBarLoading () to hide the navigation bar to load the animation after the network request succeeds or fails.

When the network request is successful and the status code is 200, the requested data callback is called back to us through success (res.data). Above, we do not break down the cause of the failure. Of course, you can also add a parameter to the failure callback to prompt the user of the reason for failure, such as an internal error in the server when res.statusCode = 500, res.statusCode =-1 prompts you to check the network, res.statusCode = 404, the address cannot be found, and so on.

Then we are creating a request function that does not display the dialog box and the user requests data in the background. in order to write less code, we share the above function, as follows

/ / request function request (url, params, success, fail) {this.requestLoading (url, params, "", success, fail)} without displaying the dialog box

We see that we finally called the requestLoading, so we can make a judgment in this function, if the prompt message message=='' does not display the dialog box.

The final code

Function request (url, params, success, fail) {this.requestLoading (url, params, "", success, fail)} / / Show the network request of the progress bar / / url: url// params of the network request: request parameter / / message: prompt of the progress bar / / success: successful callback function / / fail: failed callback function requestLoading (url, params, message, success) Fail) {console.log (params) wx.showNavigationBarLoading () if (message! = ") {wx.showLoading ({title: message,})} wx.request ({url: url, data: params, header: {/ / 'Content-Type':' application/json' 'content-type':' application/x-www-form-urlencoded'}, method: 'post' Success: function (res) {/ / console.log (res.data) wx.hideNavigationBarLoading () if (message! = ") {wx.hideLoading ()} if (res.statusCode = = 200) {success (res.data)} else {fail ()}}, fail: function (res) {wx.hideNavigationBarLoading () if (message! =") {wx.hideLoading ()} fail ()} Complete: function (res) {},} module.exports = {request: request, requestLoading: requestLoading}

It is easy to use, as follows

/ / the path modifies var network = require ("/ utils/network.js") getData:function () {network.requestLoading (URL.MY_SCORE, that.data.params, 'loading data', function (res) {/ / res is the data returned by our request API console.log (res)}, function () {wx.showToast ({title: 'failed to load data') })})} the content of "how to encapsulate network requests in WeChat Mini Programs" is introduced here. Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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