


Detailed example of encapsulation of WeChat applet wx.request
I recently tried small program development, and there are always pitfalls, but I think the request part is really ugly, so you know, I used Promise to simply encapsulate the request. The method described in this article is mainly for third-party login.
Without further ado, just post the code:
Business-related js
// 获取剩余金额 --- GET 请求无参数 getBalance: function () { api.getBalance().then(data => { let balance = data.data balance.balance = balance.balance.toFixed(2) this.setData({ balance: { ...balance } }) }) }, // 获取昨日消费数据 --- POST 请求,使用 application/x-www-form-urlencoded 传参 getLastCost: function () { let yestoday = util.transDate('', -1) let data = { subAccountIdx: 0, startDay: yestoday, endDay: yestoday, type: 0, business: 0, export: false } api.getLastCost(data, 'application/x-www-form-urlencoded', 'POST').then(data => { let lastCost = data.data.record.totalConsumeMoney lastCost = lastCost.toFixed(2) this.setData({ lastCost: lastCost }) }) }
The code above is the business part code. I don’t know if you like this method. Let’s continue. Let’s take a look at the encapsulation method and business corresponding configuration js
Use Promise to encapsulate wx.request
Most of our websites use cookies to maintain the login status, but the mini program cannot be used Cookie is used to maintain the login status, then we first obtain the cookie of the request header, and then save the cookie in the global variable (I believe it is no problem to obtain the cookie, this part will not be shown)
// wx.request 封装 var app = getApp() function wxRequest(url, config, resolve, reject) { let { data = {}, contentType = 'application/json', method = 'GET', ...other } = {...config} wx.request({ url: url, data: {...data}, method: method, header: { 'content-type': contentType, 'Cookie': app.globalData.cookie // 全局变量中获取 cookie }, success: (data) => resolve(data), fail: (err) => reject(err) }) } module.exports = { wxRequest: wxRequest }
Encapsulated code Very simple, the next step is to configure the code
Configuration js corresponding to the business
// 用 import 或者 require 引入模块 import util from '../../../util/util.js' var Promise = require('../../../plugin/promise.js') // 请注意 Promise 要手动引入,内测版是自动引入的 // 获取个人信息 const API_USERINFO = "https://www.***/get" // 获取剩余金额 const API_BALANCE = 'https://www.***/get' // 获取昨日消费数据 const API_LASTCOST = 'https://www.***/get' // 获取个人信息事件 function getUserInfo(data, contentType) { var promise = new Promise((resolve, reject) => { util.wxRequest(API_USERINFO, { data, contentType }, resolve, reject) }) // return promise return promise.then(res => { return res.data }).catch(err => { console.log(err) }) } // 获取剩余金额事件 function getBalance(data, contentType) { var promise = new Promise((resolve, reject) => { util.wxRequest(API_BALANCE, { data, contentType }, resolve, reject) }) // return promise return promise.then(res => { return res.data }).catch(err => { console.log(err) }) } // 获取昨日消费数据 function getLastCost(data, contentType, method) { var promise = new Promise((resolve, reject) => { util.wxRequest(API_LASTCOST, { data, contentType, method }, resolve, reject) }) // return promise return promise.then(res => { return res.data }).catch(err => { console.log(err) }) } module.exports = { getUserInfo: getUserInfo, getBalance: getBalance, getLastCost: getLastCost }
The above code seems to have more steps, but the advantage is that it is easy to maintain. In the business code It only focuses on the business, rather than the request itself. Content-type switching is also convenient. Of course, if you only have one method of passing parameters, it will be simpler to write it down. As a front-end novice, this is my first article. I hope it can help a few people. Personally, I most hope that the big guys will give you some advice and pointers.
Related recommendations:
WeChat applet wx.request realizes background data interaction function analysis
Mini program development--network request wx .request instance tutorial
Mini program development--wx.request asynchronous encapsulation instance tutorial
The above is the detailed content of Detailed example of encapsulation of WeChat applet wx.request. 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

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

With the popularity of mobile Internet technology and smartphones, WeChat has become an indispensable application in people's lives. WeChat mini programs allow people to directly use mini programs to solve some simple needs without downloading and installing applications. This article will introduce how to use Python to develop WeChat applet. 1. Preparation Before using Python to develop WeChat applet, you need to install the relevant Python library. It is recommended to use the two libraries wxpy and itchat here. wxpy is a WeChat machine

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

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.
