Detailed example of encapsulation of WeChat applet wx.request

小云云
Release: 2018-02-07 15:59:29
Original
4430 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!