Home WeChat Applet Mini Program Development Detailed example of encapsulation of WeChat applet wx.request

Detailed example of encapsulation of WeChat applet wx.request

Feb 07, 2018 pm 03:59 PM
encapsulation Applets

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
      })
    })
  }
Copy after login

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
}
Copy after login

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
}
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Develop WeChat applet using Python Develop WeChat applet using Python Jun 17, 2023 pm 06:34 PM

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

Implement card flipping effects in WeChat mini programs Implement card flipping effects in WeChat mini programs Nov 21, 2023 am 10:55 AM

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

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

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.

Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Alipay launched the 'Chinese Character Picking-Rare Characters' mini program to collect and supplement the rare character library Oct 31, 2023 pm 09:25 PM

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 achieves rapid conversion between mini programs and H5 How uniapp achieves rapid conversion between mini programs and H5 Oct 20, 2023 pm 02:12 PM

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

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

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

How do C++ functions improve the efficiency of GUI development by encapsulating code? How do C++ functions improve the efficiency of GUI development by encapsulating code? Apr 25, 2024 pm 12:27 PM

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.

How to operate mini program registration How to operate mini program registration Sep 13, 2023 pm 04:36 PM

Mini program registration operation steps: 1. Prepare copies of personal ID cards, corporate business licenses, legal person ID cards and other filing materials; 2. Log in to the mini program management background; 3. Enter the mini program settings page; 4. Select " "Basic Settings"; 5. Fill in the filing information; 6. Upload the filing materials; 7. Submit the filing application; 8. Wait for the review results. If the filing is not passed, make modifications based on the reasons and resubmit the filing application; 9. The follow-up operations for the filing are Can.

See all articles